Maximum average sum partition of an array
Last Updated :
20 Dec, 2022
Given an array, we partition a row of numbers A into at most K adjacent (non-empty) groups, then the score is the sum of the average of each group. What is the maximum score that can be scored?
Examples:
Input : A = { 9, 1, 2, 3, 9 }
K = 3
Output : 20
Explanation : We can partition A into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.
We could have also partitioned A into [9, 1], [2], [3, 9]. That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.
Input : A[] = { 1, 2, 3, 4, 5, 6, 7 }
K = 4
Output : 20.5
Explanation : We can partition A into [1, 2, 3, 4], [5], [6], [7]. The answer is 2.5 + 5 + 6 + 7 = 20.5.
A simple solution is to use recursion. An efficient solution is memorization where we keep the largest score upto k i.e. for 1, 2, 3... upto k;
Let memo[i][k] be the best score portioning A[i..n-1] into at most K parts. In the first group, we partition A[i..n-1] into A[i..j-1] and A[j..n-1], then our candidate partition has score average(i, j) + score(j, k-1)), where average(i, j) = (A[i] + A[i+1] + ... + A[j-1]) / (j - i). We take the highest score of these.
In total, our recursion in the general case is :
memo[n][k] = max(memo[n][k], score(memo, i, A, k-1) + average(i, j))
for all i from n-1 to 1 .
Implementation:
C++
// CPP program for maximum average sum partition
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
double memo[MAX][MAX];
// bottom up approach to calculate score
double score(int n, vector<int>& A, int k)
{
if (memo[n][k] > 0)
return memo[n][k];
double sum = 0;
for (int i = n - 1; i > 0; i--) {
sum += A[i];
memo[n][k] = max(memo[n][k], score(i, A, k - 1) +
sum / (n - i));
}
return memo[n][k];
}
double largestSumOfAverages(vector<int>& A, int K)
{
int n = A.size();
double sum = 0;
memset(memo, 0.0, sizeof(memo));
for (int i = 0; i < n; i++) {
sum += A[i];
// storing averages from starting to each i ;
memo[i + 1][1] = sum / (i + 1);
}
return score(n, A, K);
}
int main()
{
vector<int> A = { 9, 1, 2, 3, 9 };
int K = 3; // atmost partitioning size
cout << largestSumOfAverages(A, K) << endl;
return 0;
}
Java
// Java program for maximum average sum partition
import java.util.Arrays;
import java.util.Vector;
class GFG
{
static int MAX = 1000;
static double[][] memo = new double[MAX][MAX];
// bottom up approach to calculate score
public static double score(int n, Vector<Integer> A, int k)
{
if (memo[n][k] > 0)
return memo[n][k];
double sum = 0;
for (int i = n - 1; i > 0; i--)
{
sum += A.elementAt(i);
memo[n][k] = Math.max(memo[n][k],
score(i, A, k - 1) +
sum / (n - i));
}
return memo[n][k];
}
public static double largestSumOfAverages(Vector<Integer> A, int K)
{
int n = A.size();
double sum = 0;
for (int i = 0; i < memo.length; i++)
{
for (int j = 0; j < memo[i].length; j++)
memo[i][j] = 0.0;
}
for (int i = 0; i < n; i++)
{
sum += A.elementAt(i);
// storing averages from starting to each i ;
memo[i + 1][1] = sum / (i + 1);
}
return score(n, A, K);
}
// Driver code
public static void main(String[] args)
{
Vector<Integer> A = new Vector<>(Arrays.asList(9, 1, 2, 3, 9));
int K = 3;
System.out.println(largestSumOfAverages(A, K));
}
}
// This code is contributed by sanjeev2552
Python3
# Python3 program for maximum average sum partition
MAX = 1000
memo = [[0.0 for i in range(MAX)]
for i in range(MAX)]
# bottom up approach to calculate score
def score(n, A, k):
if (memo[n][k] > 0):
return memo[n][k]
sum = 0
i = n - 1
while(i > 0):
sum += A[i]
memo[n][k] = max(memo[n][k], score(i, A, k - 1) +
int(sum / (n - i)))
i -= 1
return memo[n][k]
def largestSumOfAverages(A, K):
n = len(A)
sum = 0
for i in range(n):
sum += A[i]
# storing averages from starting to each i ;
memo[i + 1][1] = int(sum / (i + 1))
return score(n, A, K)
# Driver Code
if __name__ == '__main__':
A = [9, 1, 2, 3, 9]
K = 3 # atmost partitioning size
print(largestSumOfAverages(A, K))
# This code is contributed by
# Surendra_Gangwar
C#
// C# program for maximum average sum partition
using System;
using System.Collections.Generic;
class GFG
{
static int MAX = 1000;
static double[,] memo = new double[MAX, MAX];
// bottom up approach to calculate score
public static double score(int n,
List<int> A, int k)
{
if (memo[n, k] > 0)
return memo[n, k];
double sum = 0;
for (int i = n - 1; i > 0; i--)
{
sum += A[i];
memo[n, k] = Math.Max(memo[n, k],
score(i, A, k - 1) +
sum / (n - i));
}
return memo[n, k];
}
public static double largestSumOfAverages(List<int> A,
int K)
{
int n = A.Count;
double sum = 0;
for (int i = 0;
i < memo.GetLength(0); i++)
{
for (int j = 0;
j < memo.GetLength(1); j++)
memo[i, j] = 0.0;
}
for (int i = 0; i < n; i++)
{
sum += A[i];
// storing averages from
// starting to each i;
memo[i + 1, 1] = sum / (i + 1);
}
return score(n, A, K);
}
// Driver code
public static void Main(String[] args)
{
int [] arr = {9, 1, 2, 3, 9};
List<int> A = new List<int>(arr);
int K = 3;
Console.WriteLine(largestSumOfAverages(A, K));
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// JavaScript program for maximum average sum partition
let MAX = 1000;
let memo = new Array(MAX).fill(0).map(() => new Array(MAX).fill(0));
// bottom up approach to calculate score
function score(n, A, k) {
if (memo[n][k] > 0)
return memo[n][k];
let sum = 0;
for (let i = n - 1; i > 0; i--) {
sum += A[i];
memo[n][k] = Math.max(memo[n][k], score(i, A, k - 1) +
sum / (n - i));
}
return memo[n][k];
}
function largestSumOfAverages(A, K) {
let n = A.length;
let sum = 0;
for (let i = 0; i < n; i++) {
sum += A[i];
// storing averages from starting to each i ;
memo[i + 1][1] = sum / (i + 1);
}
return score(n, A, K);
}
let A = [9, 1, 2, 3, 9];
let K = 3; // atmost partitioning size
document.write(largestSumOfAverages(A, K) + "<br>");
</script>
Above problem can now be easily understood as dynamic programming.
Let dp(i, k) be the best score partitioning A[i:j] into at most K parts. If the first group we partition A[i:j] into ends before j, then our candidate partition has score average(i, j) + dp(j, k-1)). Recursion in the general case is dp(i, k) = max(average(i, N), (average(i, j) + dp(j, k-1))). We can precompute the prefix sums for fast execution of out code.
Implementation:
C++
// CPP program for maximum average sum partition
#include <bits/stdc++.h>
using namespace std;
double largestSumOfAverages(vector<int>& A, int K)
{
int n = A.size();
// storing prefix sums
double pre_sum[n+1];
pre_sum[0] = 0;
for (int i = 0; i < n; i++)
pre_sum[i + 1] = pre_sum[i] + A[i];
// for each i to n storing averages
double dp[n] = {0};
double sum = 0;
for (int i = 0; i < n; i++)
dp[i] = (pre_sum[n] - pre_sum[i]) / (n - i);
for (int k = 0; k < K - 1; k++)
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
dp[i] = max(dp[i], (pre_sum[j] -
pre_sum[i]) / (j - i) + dp[j]);
return dp[0];
}
// Driver code
int main()
{
vector<int> A = { 9, 1, 2, 3, 9 };
int K = 3; // atmost partitioning size
cout << largestSumOfAverages(A, K) << endl;
return 0;
}
Java
// Java program for maximum average sum partition
import java.util.*;
class GFG
{
static double largestSumOfAverages(int[] A, int K)
{
int n = A.length;
// storing prefix sums
double []pre_sum = new double[n + 1];
pre_sum[0] = 0;
for (int i = 0; i < n; i++)
pre_sum[i + 1] = pre_sum[i] + A[i];
// for each i to n storing averages
double []dp = new double[n];
double sum = 0;
for (int i = 0; i < n; i++)
dp[i] = (pre_sum[n] - pre_sum[i]) / (n - i);
for (int k = 0; k < K - 1; k++)
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
dp[i] = Math.max(dp[i], (pre_sum[j] -
pre_sum[i]) / (j - i) + dp[j]);
return dp[0];
}
// Driver code
public static void main(String[] args)
{
int []A = { 9, 1, 2, 3, 9 };
int K = 3; // atmost partitioning size
System.out.println(largestSumOfAverages(A, K));
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 program for maximum average
# sum partition
def largestSumOfAverages(A, K):
n = len(A);
# storing prefix sums
pre_sum = [0] * (n + 1);
pre_sum[0] = 0;
for i in range(n):
pre_sum[i + 1] = pre_sum[i] + A[i];
# for each i to n storing averages
dp = [0] * n;
sum = 0;
for i in range(n):
dp[i] = (pre_sum[n] -
pre_sum[i]) / (n - i);
for k in range(K - 1):
for i in range(n):
for j in range(i + 1, n):
dp[i] = max(dp[i], (pre_sum[j] -
pre_sum[i]) /
(j - i) + dp[j]);
return int(dp[0]);
# Driver code
A = [ 9, 1, 2, 3, 9 ];
K = 3; # atmost partitioning size
print(largestSumOfAverages(A, K));
# This code is contributed by Rajput-Ji
C#
// C# program for maximum average sum partition
using System;
using System.Collections.Generic;
class GFG
{
static double largestSumOfAverages(int[] A,
int K)
{
int n = A.Length;
// storing prefix sums
double []pre_sum = new double[n + 1];
pre_sum[0] = 0;
for (int i = 0; i < n; i++)
pre_sum[i + 1] = pre_sum[i] + A[i];
// for each i to n storing averages
double []dp = new double[n];
for (int i = 0; i < n; i++)
dp[i] = (pre_sum[n] - pre_sum[i]) / (n - i);
for (int k = 0; k < K - 1; k++)
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
dp[i] = Math.Max(dp[i], (pre_sum[j] -
pre_sum[i]) / (j - i) + dp[j]);
return dp[0];
}
// Driver code
public static void Main(String[] args)
{
int []A = { 9, 1, 2, 3, 9 };
int K = 3; // atmost partitioning size
Console.WriteLine(largestSumOfAverages(A, K));
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// javascript program for maximum average sum partition
function largestSumOfAverages(A , K) {
var n = A.length;
// storing prefix sums
var pre_sum = Array(n + 1).fill(-1);
pre_sum[0] = 0;
for (var i = 0; i < n; i++)
pre_sum[i + 1] = pre_sum[i] + A[i];
// for each i to n storing averages
var dp = Array(n).fill(-1);
var sum = 0;
for (var i = 0; i < n; i++)
dp[i] = (pre_sum[n] - pre_sum[i]) / (n - i);
for (k = 0; k < K - 1; k++)
for (i = 0; i < n; i++)
for (j = i + 1; j < n; j++)
dp[i] = Math.max(dp[i], (pre_sum[j] - pre_sum[i]) / (j - i) + dp[j]);
return dp[0];
}
// Driver code
var A = [ 9, 1, 2, 3, 9 ];
var K = 3; // atmost partitioning size
document.write(largestSumOfAverages(A, K));
// This code is contributed by umadevi9616
</script>
Time Complexity: O(n2*K)
Auxiliary Space: O(n)
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem