Ask Your Question
3

What is the length of the longest subsequence of positive numbers in a list whose sum does not exceed k?

asked 2023-03-12 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-11-21 10:00:00 +0000

huitzilopochtli gravatar image

Let the list be $a1, a2, \dots, an$. We can use dynamic programming to solve this problem. Let $dp[i][j]$ represent the length of the longest subsequence of positive numbers in the list $a1, a2, \dots, ai$ whose sum does not exceed $j$. We can calculate $dp[i][j]$ by considering two cases:

Case 1: We include $ai$ in the subsequence. In this case, $dp[i][j]$ is equal to $dp[i-1][j-ai] + 1$, since we need to find the longest subsequence that does not exceed $j-ai$, and then add $ai$ to it.

Case 2: We do not include $a_i$ in the subsequence. In this case, $dp[i][j]$ is equal to $dp[i-1][j]$, since we can use the longest subsequence we found in the previous step.

Therefore, we have the following recurrence relation:

$$ dp[i][j] = \max(dp[i-1][j],\ dp[i-1][j-a_i] + 1), $$

with the base case $dp[0][j] = 0$ for all $j$, and the answer is $\max{dp[n][j]}$ such that $j \leq k$.

The time complexity of this algorithm is $\mathcal{O}(nk)$, where $n$ is the length of the list and $k$ is the maximum sum allowed.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-03-12 11:00:00 +0000

Seen: 11 times

Last updated: Nov 21 '21