Difference between sum of numbers in two set is minimal

Given an array of positive integers, divide the array into two subsets such that the difference between the sum of the subsets is as small as possible.

For example, given [5, 10, 15, 20, 25], return the sets {10, 25} and {5, 15, 20}, which has a difference of 5, which is the smallest possible difference.

Example:

Input:  arr = {5, 10, 15, 20, 25}
Output: 5

Approach

C++

#include <bits/stdc++.h>
using namespace std;

#define MXN 55
int arr[MXN];
int dp[MXN][MXN * MXN];

int main()
{

    vector<intarr = {510152025};
    for (int i = 0i < MXN; i++)
    {
        fill(dp[i], dp[i] + MXN * MXN0);
    }
    int sum = 0;
    int N = arr.size();
    for (int i = 0i < Ni++)
    {
        sum += arr[i];
    }
    dp[0][0] = 1;
    for (int i = 1i <= Ni++)
    {
        for (int j = sumj >= 0j--)
        {
            dp[i][j] |= (dp[i - 1][j] |
                         (j >= arr[i - 1] ? 
                         dp[i - 1][j - arr[i - 1]] : 0));
        }
    }

    int res = sum;

    for (int i = 0i <= sum / 2i++)
    {
        if (dp[N][i])
        {
            res = min(resabs(i - (sum - i)));
        }
    }

    cout << res << "\n";
    return 0;
}


No comments:

Post a Comment