Length of the Longest Subsequence That Sums to Target

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.

Example 1
Inputnums = [1,2,3,4,5], target = 9
Output3
There are 3 subsequences with a sum equal to 9: [4,5], [1,3,5], and [2,3,4], and the longest subsequences have length 3.
Example 2
Inputnums = [4,1,3,2,1,5], target = 7
Output4
There are 5 subsequences with a sum equal to 7, and the longest subsequence is [1,3,2,1] with length 4.

Constraints

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 1000
  • 1 <= target <= 1000

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate