Largest Sum of Averages in C++


Suppose we partition a row of numbers A into at most K adjacent groups, then we will set score as the sum of the average of each group. We have to find that what is the largest score that we can achieve. Suppose A = [9,1,2,3,9] and K is 3, then the result will be 20, this is because, the best choice is to partition A into [9], [1, 2, 3], [9]. So the answer is 9 + (1 + 2 + 3) / 3 + 9 = 20. We could have also partitioned A into [9, 1], [2], [3, 9],

To solve this, we will follow these steps −

  • Define a matrix dp
  • Define a recursive method solve(), This will take array A, index and k
  • if index >= size of A, then return 0
  • if k is 0, then return -100000
  • if dp[index, k] is not – 1, then return dp[index, k]
  • ret := -inf and sum := 0
  • for i in range index to size of A – 1
    • sum := sum + A[i]
    • ret := max of ret and sum/(i – index + 1) + solve(A, i + 1, k – 1)
  • set dp[index, k] := ret and return.
  • From the main method, do the following −
  • n := size of A
  • dp := a matrix n x (K + 1), fill it with – 1
  • return solve(A, 0, K)

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   vector < vector <double> > dp;
   double solve(vector <int>& A, int idx, int k){
      if(idx >= A.size()) return 0;
      if(!k) return -100000;
      if(dp[idx][k] != -1) return dp[idx][k];
      double ret = INT_MIN;
      double sum = 0;
      for(int i = idx; i < A.size(); i++){
         sum += A[i];
         ret = max(sum / (i - idx + 1) + solve(A, i + 1, k - 1), ret);
      }
      return dp[idx][k] = ret;
   }
   double largestSumOfAverages(vector<int>& A, int K) {
      int n = A.size();
      dp = vector < vector <double> > (n, vector <double>(K + 1, -1));
      return solve(A, 0, K);
   }
};
main(){
   vector<int> v = {9,1,2,3,9};
   Solution ob;
   cout << (ob.largestSumOfAverages(v, 3));
}

Input

[9,1,2,3,9]
3

Output

20

Updated on: 04-May-2020

79 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements