Program to find sum of k non-overlapping sublists whose sum is maximum in C++

C++Server Side ProgrammingProgramming

Suppose we have a list of numbers called nums, and another value k, we have to find the k non-overlapping, non-empty sublists such that the sum of their sums is maximum. We can consider k is less than or equal to the size of nums.

So, if the input is like nums = [11, -1, 2, 1, 6, -24, 11, -9, 6] k = 3, then the output will be 36, as we can select the sublists [11, -1, 2, 1, 6], [11], and [6] to get sums of [19, 11, 6] = 36.

To solve this, we will follow these steps −

  • n := size of nums
  • if n is same as 0 or k is same as 0, then −
    • return 0
  • Define an array hi of size k + 1 and fill with -inf,
  • Define another array open of size k + 1 and fill with -inf
  • hi[0] := 0
  • for each num in nums −
    • Define an array nopen of size k + 1 and fill with -inf
    • for initialize i := 1, when i <= k, update (increase i by 1), do
      • if open[i] > -inf, then −
        • nopen[i] := open[i] + num
      • if hi[i - 1] > -inf, then −
        • nopen[i] := maximum of nopen[i] and hi[i - 1] + num
    • open := move(nopen)
    • for initialize i := 1, when i <= k, update (increase i by 1), do
      • hi[i] := maximum of hi[i] and open[i]
  • return hi[k]

Example (C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int>& nums, int k) {
   int n = nums.size();
   if (n == 0 || k == 0)
      return 0;
   vector<int> hi(k + 1, INT_MIN), open(k + 1, INT_MIN);
   hi[0] = 0;
   for (int num : nums) {
      vector<int> nopen(k + 1, INT_MIN);
      for (int i = 1; i <= k; ++i) {
         if (open[i] > INT_MIN)
            nopen[i] = open[i] + num;
         if (hi[i - 1] > INT_MIN)
            nopen[i] = max(nopen[i], hi[i - 1] + num);
      }
      open = move(nopen);
      for (int i = 1; i <= k; ++i)
      hi[i] = max(hi[i], open[i]);
   }
   return hi[k];
}
int main(){
   vector<int> v = {11, -1, 2, 1, 6, -24, 11, -9, 6};
   int k = 3;
   cout << solve(v, 3);
}

Input

{11, -1, 2, 1, 6, -24, 11, -9, 6}, 3

Output

36
raja
Published on 12-Dec-2020 10:07:09
Advertisements