Length of the Longest Subsequence That Sums to Target - Problem

Given a 0-indexed array of integers nums and an integer target, find the length of the longest subsequence of nums that sums up to target.

A subsequence is derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, from array [1,2,3,4], valid subsequences include [1,3], [2,4], and [1,2,3,4].

Your task: Return the maximum possible length of such a subsequence. If no subsequence exists that sums to target, return -1.

Example: For nums = [1,2,3,2] and target = 4, the longest subsequence is [1,3] or [2,2], both with length 2.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1,2,3,2], target = 4
โ€บ Output: 2
๐Ÿ’ก Note: The longest subsequence that sums to 4 is either [1,3] or [2,2], both have length 2.
example_2.py โ€” Multiple Elements
$ Input: nums = [1,1,1,1], target = 3
โ€บ Output: 3
๐Ÿ’ก Note: We can select any 3 elements from [1,1,1,1] to get sum 3, giving us length 3.
example_3.py โ€” No Solution
$ Input: nums = [2,4,6], target = 5
โ€บ Output: -1
๐Ÿ’ก Note: No subsequence of [2,4,6] can sum to 5, so we return -1.

Constraints

  • 1 โ‰ค nums.length โ‰ค 1000
  • 1 โ‰ค nums[i] โ‰ค 1000
  • 1 โ‰ค target โ‰ค 1000
  • All elements in nums are positive integers

Visualization

Tap to expand
๐ŸŽฏ Treasure Hunt: Dynamic Programming StrategyCoins: [1๐Ÿ’ฐ, 2๐Ÿ’ฐ, 3๐Ÿ’ฐ, 2๐Ÿ’ฐ] โ†’ Target: 4๐Ÿ’ฐTreasure Map (DP Table):0๐Ÿ’ฐ
0๐Ÿช™Start1๐Ÿ’ฐ
1๐Ÿช™
2๐Ÿ’ฐ
1๐Ÿช™
3๐Ÿ’ฐ
2๐Ÿช™
4๐Ÿ’ฐ
2๐Ÿช™
TARGET!Optimal Paths Found:Path 1: Select coins [1๐Ÿ’ฐ, 3๐Ÿ’ฐ] โ†’ Sum = 4๐Ÿ’ฐ, Length = 2๐Ÿช™Path 2: Select coins [2๐Ÿ’ฐ, 2๐Ÿ’ฐ] โ†’ Sum = 4๐Ÿ’ฐ, Length = 2๐Ÿช™Maximum coins collected: 2๐Ÿช™DP Transition:For each coin value 'v' and each sum 's':dp[s] = max(dp[s], dp[s-v] + 1)"Can we get better result by including this coin?"โšก Process backwards to avoid double-counting!
Understanding the Visualization
1
Initialize Treasure Map
Create a map showing the maximum coins needed for each treasure value from 0 to target
2
Process Each Coin
For each coin type, update the map by considering whether to include it
3
Backward Update
Update from highest to lowest values to avoid using the same coin twice
4
Find Optimal Path
The answer is the maximum coins achievable for the target treasure value
Key Takeaway
๐ŸŽฏ Key Insight: This problem is a variant of the unbounded knapsack where we maximize count instead of value. DP lets us build optimal solutions incrementally!
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
42.0K Views
Medium Frequency
~25 min Avg. Time
1.4K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen