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 55int arr[MXN];int dp[MXN][MXN * MXN];int main(){vector<int> arr = {5, 10, 15, 20, 25};for (int i = 0; i < MXN; i++){fill(dp[i], dp[i] + MXN * MXN, 0);}int sum = 0;int N = arr.size();for (int i = 0; i < N; i++){sum += arr[i];}dp[0][0] = 1;for (int i = 1; i <= N; i++){for (int j = sum; j >= 0; j--){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 = 0; i <= sum / 2; i++){if (dp[N][i]){res = min(res, abs(i - (sum - i)));}}cout << res << "\n";return 0;}
No comments:
Post a Comment