-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
32 lines (25 loc) · 762 Bytes
/
Copy pathsolution.java
File metadata and controls
32 lines (25 loc) · 762 Bytes
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
class Solution {
public int countPartitions(int[] arr, int diff) {
int totalSum = 0;
// Calculate total sum
for (int num : arr) {
totalSum += num;
}
// If totalSum + diff is odd, answer is impossible
if ((totalSum + diff) % 2 != 0) {
return 0;
}
int target = (totalSum + diff) / 2;
// dp[j] = number of ways to make sum j
int[] dp = new int[target + 1];
// One way to form sum 0
dp[0] = 1;
for (int num : arr) {
// Traverse backwards
for (int j = target; j >= num; j--) {
dp[j] += dp[j - num];
}
}
return dp[target];
}
}