The opposite question:
Maximum length subsequence with positive-sum <= K is in fact the standard 01 Knapsack problem.
The solution for it is pretty straightforward:
int solve(const vector<int> &A, int K) {
int dp[A.size()+1][K+1];
int i, j;
// Base Cases
for(i=0; i<= K; i++)
dp[0][i] = 0;
for(i=0; i<= A.size(); i++)
dp[i][0] = 0;
for(i=1; i <= A.size(); i++)
{
for(j=1; j<= K; j++)
{
dp[i][j] = dp[i-1][j];
if(A[i-1] <= j)
dp[i][j] = max(dp[i][j], 1 + dp[i-1][j-A[i-1]]);
}
}
return dp[A.size()][K]
I am having a tough time thinking how Minimum length subsequence with sum <= K could be implemented along the same lines.
Example:
A = [14, 10, 4]
K = 14
Minimum Length Subsequence = 14
Maximum Length Subsequence = 10, 4 (Arrived from Knapsack)
Its certainly not as easy as just changing the max to min as then the answer shall always be the base case. Which leads me to think, Do we need to tweak the base case? I am stuck here and need some push.
Any ideas on how one should be solving this problem?