Length of the Longest Subsequence That Sums to Target - Problem
You are given a 0-indexed array of integers nums, and an integer target.
Return the length of the longest subsequence of nums that sums up to target. If no such subsequence exists, return -1.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,3], target = 4
›
Output:
2
💡 Note:
The longest subsequence that sums to 4 is [1,3] with length 2. We can also achieve sum 4 with just [4] if 4 was in the array, but [1,3] gives us the maximum length of 2.
Example 2 — Multiple Solutions
$
Input:
nums = [1,1,5,4,5], target = 6
›
Output:
3
💡 Note:
We can form target 6 with [1,1,4] (length 3) or [1,5] (length 2). The longest subsequence has length 3.
Example 3 — Impossible Target
$
Input:
nums = [1,2,3], target = 10
›
Output:
-1
💡 Note:
No subsequence can sum to 10 since the maximum possible sum is 1+2+3=6.
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ 1000
- 1 ≤ target ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of integers and target sum
2
Process
Find all subsequences that sum to target
3
Output
Return length of longest valid subsequence
Key Takeaway
🎯 Key Insight: This is a variant of the unbounded knapsack problem where we maximize the count of items instead of their value.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code