-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
33 lines (26 loc) · 889 Bytes
/
Copy pathsolution.cpp
File metadata and controls
33 lines (26 loc) · 889 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
33
class Solution {
public:
int countPartitions(vector<int>& arr, int diff) {
int totalSum = 0;
// Calculate total sum of array
for (int num : arr) {
totalSum += num;
}
// If totalSum + diff is odd, partition is impossible
if ((totalSum + diff) % 2 != 0) {
return 0;
}
int target = (totalSum + diff) / 2;
// dp[j] = number of ways to make sum j
vector<int> dp(target + 1, 0);
// One way to make sum 0 -> choose nothing
dp[0] = 1;
for (int num : arr) {
// Traverse backwards to avoid reusing same element
for (int j = target; j >= num; j--) {
dp[j] += dp[j - num];
}
}
return dp[target];
}
};