0/1 Knapsack
Each item can only be selected once.
Bottom-up Approach
Let dp[i][c]
represents the maximum profit for capacity c
for the first i
items.
Recurrence:
First attempt uses O(N*C)
space:
O(N*C)
space:Second attempt uses O(C)
space:
O(C)
space:Dimension reduction: use the same array for the previous & next iteration.
In order to update dp[c]
, we would access dp[c]
and dp[c-weights[i]]
.
dp[c]
is fine, whereas dp[c-weights[i]]
might be overridden since weights[i] > 0
as we need the value from previous iteration. Solution is to traverse from capacity -> 0
instead.
Equal Subset Sum Partition
Problem Statement
Given a set of positive numbers, find if we can partition it into two subsets such that the sum of elements in both the subsets is equal.
Recurrence
dp[i][s]
represents whether it's possible (True/False
) to have sum of s
for the first i
items.
dp[i][s] = dp[i-1][s] or dp[i-1][s-a[i]] iff s-a[i] > 0
First Attempt
Second Attempt
// TODO
Subset Sum
Problem Statement
Given a set of positive numbers, determine if there exists a subset whose sum is equal to a given number S
.
Recurrence
dp[i][s] = dp[i-1][s] or dp[i-1][s-num[i]] iff s-num[i] > 0
dp[s] = dp[s] or dp[s-num[i]]
while traversing from sum -> 0
.
Solution
Minimum Subset Sum Difference
Problem Statement
Given a set of positive numbers, partition the set into two subsets with a minimum difference between their subset sums.
Recurrence
// TODO
Solution
Last updated