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
Length of Longest Subsequence That Sums to Target INPUT nums array: 1 idx 0 2 idx 1 3 idx 2 target: 4 Possible subsequences: [1], [2], [3], [1,2] [1,3], [2,3], [1,2,3] [], etc... ALGORITHM (DP) 1 Initialize DP dp[0]=0, rest=-infinity 2 Iterate nums Process each element 3 Update DP table dp[j]=max(dp[j],dp[j-n]+1) 4 Return result dp[target] or -1 DP Table (sum --> length) sum 0 1 2 3 4 len 0 1 1 2 2 1+3=4 (len 2) or 2+2 N/A Best: [1,3] with length 2 FINAL RESULT Longest Subsequence: 1 3 + 1 + 3 = 4 (OK) Output: 2 Length = 2 Subsequence [1,3] sums to target 4 VALID OK Key Insight: Use Dynamic Programming where dp[s] = maximum length of subsequence that sums to s. For each number n in nums, update dp[j] = max(dp[j], dp[j-n]+1) for j from target down to n. Time: O(n * target), Space: O(target). Return dp[target] if reachable, else -1. TutorialsPoint - Length of the Longest Subsequence That Sums to Target | DP Approach
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 6
12.5K Views
Medium Frequency
~25 min Avg. Time
485 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