-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path140_minimum_sum_partitions.cpp
More file actions
83 lines (66 loc) · 1.6 KB
/
Copy path140_minimum_sum_partitions.cpp
File metadata and controls
83 lines (66 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// https://practice.geeksforgeeks.org/problems/minimum-sum-partition/0
#include <bits/stdc++.h>
using namespace std;
// logic: maintain maximum sum found till now in partition sum problem
// and 2 partitions each of s1 = (max_sum) & s2 = (total_sum - max_sum) there diff will
// definitly be minimum ans = abs(s1-s2)
int min_partition_sum(vector<int> a, int n)
{
int total_sum = 0;
for (int i = 0; i < n; ++i)
total_sum += a[i];
int max_sum = INT_MIN;
int k = total_sum / 2;
vector <vector <bool> > SS(n + 1, vector<bool>(k + 1));
// bool SS[n + 1][k + 1];
// initialize first col to true
// with 0 elements sum 0 is always possible
for (int i = 0; i < n + 1; ++i)
SS[i][0] = true;
// initialize first row to false
// with 0 elements sum>0 is not possible
for (int j = 1; j < k + 1; ++j)
SS[0][j] = false;
for (int i = 1; i < n + 1; ++i)
{
for (int j = 1; j < k + 1; ++j)
{
if (j >= a[i - 1])
{
// when we not include cur element or we include it
SS[i][j] = (SS[i - 1][j] || SS[i - 1][j - a[i - 1]]);
// if j sum possible
if (SS[i][j] && max_sum < j)
max_sum = j;
}
else
{
// we are not able to include it
SS[i][j] = SS[i - 1][j];
}
}
}
int s1 = max_sum, s2 = total_sum - max_sum;
return abs(s1 - s2);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i)
cin >> a[i];
cout << min_partition_sum(a, n) << endl;
}
return 0;
}