Split Array Largest Sum in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of positive integers and one value m. We can divide this array into m number of contiguous subarrays. We have to devise an algorithm to minimize the largest sum among these m subarrays.

So if the array is say [7,2,4,10,9], and m = 2, then the sum will be 19, as we can make two subarrays like [7,2,4] and [10,9], then the subarray with largest sum is 19.

To solve this, we will follow these steps −

  • Define a function splitArray(), this will take an array v, m,
  • n := size of v
  • make one array dp of size
  • make another array sum of size n
  • sum[0] := v[0]
  • for initialize i := 1, when i < n, update (increase i by 1), do −
    • sum[i] := sum[i - 1] + v[i]
  • dp[0] := sum[n - 1]
  • for initialize i := 1, when i < n, update (increase i by 1), do −
    • dp[i] := sum[n - 1] - sum[i - 1]
  • for initialize i := 1, when i < m, update (increase i by 1), do −
    • for initialize start := 0, when start < n - i, update (increase start by 1), do −
      • for initialize end := start + 1, when end <= n - i, update (increase end by 1), do −
      • dp[start] := minimum of dp[start] and maximum of (sum[end - 1] when start is 0, otherwise sum[end - 1] - sum[start - 1]) and dp[end]
  • return dp[0]

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
public:
   int splitArray(vector<int>& v, int m) {
      int n = v.size();
      vector <long long int > dp(n);
      vector <long long int> sum(n);
      sum[0] = v[0];
      for(int i =1;i<n;i++)sum[i] =sum[i-1]+v[i];
      dp[0] = sum[n-1];
      for(int i =1;i<n;i++){
         dp[i] = sum[n-1] - sum[i-1];
      }
      for(int i =1;i<m;i++){
         for(int start = 0;start<n-i;start++){
            for(int end = start+1;end<=n-i;end++){
               dp[start] = min(dp[start],max((start==0?sum[end-1]:sum[end-1]-sum[start-1]),dp[end]));
            }
         }
      }
      return dp[0];
   }
};
main(){
   Solution ob;
   vector<int> v = {7,2,4,10,9};
   cout << (ob.splitArray(v, 2));
}

Input

[7,2,4,10,9]
2

Output

19
raja
Published on 01-Jun-2020 10:47:54
Advertisements