0

This is my code for Minimum Sum Partition using DP.

#include<bits/stdc++.h>
using namespace std;
int minPart(vector<int>v)
{
  int sum = accumulate(v.begin(),v.end(),0);
  bool dp[v.size()+1][sum+1];
  fill(*dp,*dp+(v.size()+1)*(sum+1),false);
  for(int i=0;i<=v.size();i++)
  {
    dp[i][0]=true;
    for(int j=1;i>0 && j<=sum;j++)
    {
      dp[i][j]=dp[i-1][j];
      if(v[i-1]<=j)
        dp[i][j] |= dp[i-1][j-v[i-1]];
    }
  }
  int j = sum/2;
  while(j>=0 && !dp[v.size()][j]){
    j--;
  }
  return sum-2*j;
}
int main()
{
  vector<int> v = {10,20,15,5,25};
  cout<<minPart(v)<<endl;
  return 0;
}

I also want to find the subset's which result in the minimum difference of sum.

For Example for the set {1,6,11,5}, the min difference is 1 and the subset's are {1,5,6} {11}. I want to print both the subset's {1,5,6},{11} .

Is there any efficient way to find print both the subset's which result in the min sum difference?

  • 1
    `bool dp[v.size()+1][sum+1];` is not C++. – Quimby Sep 09 '20 at 19:37
  • I think that with dynamic programming and memoization can be done in O(n^2), and i can't think in other way – Berto99 Sep 09 '20 at 19:37
  • @Quimby thanks for mentioning I changed the tag. – HRISHIT PRASAD BISWAS Sep 09 '20 at 19:47
  • @Berto99 I think the time complexity of my code is O(n*sum), it's a Pseudo Polynomial Time Complexity and it is bottom-up memoized approach. – HRISHIT PRASAD BISWAS Sep 09 '20 at 19:49
  • @HRISHITPRASADBISWAS Sorry, I was not clear, VLAs are not present in any version of standard C++. They were meant to be in C99 but were made optional in C11, so some compilers still support them even in C++. Use `std::vector`. Arrays always require compile-time constant size. – Quimby Sep 09 '20 at 19:50
  • [You should never use #include ](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h). – rsjaffe Sep 09 '20 at 20:16

0 Answers0