-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpartition.java
More file actions
51 lines (35 loc) · 1.18 KB
/
partition.java
File metadata and controls
51 lines (35 loc) · 1.18 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
class Solution {
public int minimumDifference(int[] nums) {
int n = nums.length;
int sum = 0;
for (int i = 0; i < n; i++) {
sum += nums[i];
}
boolean[][] dp = new boolean[n][sum + 1];
for (int i = 0; i < n; i++) {
dp[i][0] = true;
}
if (nums[0] <= sum) {
dp[0][sum] = true;
}
// Fill the dp table
for (int ind = 1; ind < n; ind++) {
for (int target = 1; target <= sum; target++) {
boolean notTaken = dp[ind - 1][target];
boolean taken = false;
if (nums[ind] <= target) {
taken = dp[ind - 1][target - nums[ind]];
}
dp[ind][target] = notTaken || taken;
}
}
int mini = Integer.MAX_VALUE;
for (int i = 0; i <= sum; i++) {
if (dp[n - 1][i]) {
int diff = Math.abs(i - (sum - i));
mini = Math.min(mini, diff);
}
}
return mini;
}
}