Program to find maximum sum of two sets where sums are equal in C++

C++Server Side ProgrammingProgramming

Suppose we have a list of numbers called nums, now find two sets as their sums are same and maximum, then find sum value.

So, if the input is like nums = [2, 5, 4, 6], then the output will be 6, as the sets are [2, 4] and [6].

To solve this, we will follow these steps −

  • sum := 0
  • for each number i in nums, do
    • sum := sum + i
  • n := size of nums
  • Define one 2D array dp of size (n + 1) x (2 * sum + 5) and fill with -1
  • dp[0, sum] := 0
  • for initialize i := 1, when i <= n, update (increase i by 1), do −
    • x := nums[i - 1]
    • for initialize j := 0, when j < 2 * sum + 5, update (increase j by 1), do −
      • if j - x >= 0 and dp[i - 1, j - x] is not equal to -1, then ^−
        • dp[i, j] := maximum of dp[i, j] and (dp[i - 1, j - x] + x)
      • if j + x < (2 * sum + 5) and dp[i - 1, j + x] is not equal to -1, then −
        • dp[i, j] := maximum of dp[i, j] and (dp[i - 1, j + x])
      • dp[i, j] := maximum of dp[i, j] and dp[i - 1, j]
  • return dp[n, sum]

Example (C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int solve(vector<int>& nums) {
      int sum = 0;
      for (int i : nums) sum += i;
      int n = nums.size();
      vector<vector<int> > dp(n + 1, vector<int>(2 * sum + 5, -1));
      dp[0][sum] = 0;
      for (int i = 1; i <= n; i++) {
         int x = nums[i - 1];
         for (int j = 0; j < 2 * sum + 5; j++) {
            if (j - x >= 0 && dp[i - 1][j - x] != -1) {
               dp[i][j] = max(dp[i][j], dp[i - 1][j - x] + x);
            }
            if (j + x < 2 * sum + 5 && dp[i - 1][j + x] != -1) {
               dp[i][j] = max(dp[i][j], dp[i - 1][j + x]);
            }
            dp[i][j] = max(dp[i][j], dp[i - 1][j]);
         }
      }
      return dp[n][sum];
   }
};
int solve(vector<int>& nums) {
   return (new Solution())->solve(nums);
}
main(){
   vector<int> v = {2, 5, 4, 6};
   cout << solve(v);
}

Input

{2, 5, 4, 6}

Output

6
raja
Published on 12-Dec-2020 10:23:56
Advertisements