I am working on some review material for dynamic programming. I need to come up with how the subproblems should be divided, work out the base case, and come up with the recursive formula.
Given n positive integers a1,a2,…,an, a number k and a target W, we want to select a subset T with exactly k elements whose sum is closest to W. Each element can be chosen only once. Define a subproblem with 3 parameters (ie, C[x,y,z] = …).
I have only worked with a few dynamic programming examples, and have never worked with one that needs 3 parameters in defining the subproblem. I am really lost here. If anyone can shine some light that would be great.
My best guess for what the subproblem should be is:
C[x,y,z] = x number of elements from {a1,…ay} where the sum is exactly z
But I have no idea if this is correct.
One way to break this down into three parameters is:
Base case is C[0,0,0] = true, C[0,i > 0,j > 0] = false
Recursive case is:
This uses space O(n^2 * max(a_i)) (can be reduced to O(n*max(a_i)) by discarding C[i,,] as it is used)
Then just search C[n,i,j] for j near z for the final answer.
As a loop…
As recursive function: