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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code