Length of the Longest Subsequence That Sums to Target — LeetCode 2915 Python Solution

MediumArrayDynamic Programming
Problem
#2915
Reading time
2 min

The 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.

Example

Input
nums = [1,2,3,4,5], target = 9
Output
3
Explanation
There are 3 subsequences with a sum equal to 9: [4,5], [1,3,5], and [2,3,4]. The longest subsequences are [1,3,5], and [2,3,4]. Hence, the answer is 3.

Python solution

Python
class Solution:
    def lengthOfLongestSubsequence(self, nums: List[int], target: int) -> int:
        n = len(nums)
        f = [[-inf] * (target + 1) for _ in range(n + 1)]
        f[0][0] = 0
        for i, x in enumerate(nums, 1):
            for j in range(target + 1):
                f[i][j] = f[i - 1][j]
                if j >= x:
                    f[i][j] = max(f[i][j], f[i - 1][j - x] + 1)
        return -1 if f[n][target] <= 0 else f[n][target]

Complexity

MeasureComplexity
TimeO(n\times target)
SpaceO(n\times target) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2915. Length of the Longest Subsequence That Sums to Target is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2915. Length of the Longest Subsequence That Sums to Target?
LeetCode 2915. Length of the Longest Subsequence That Sums to Target is rated Medium on LeetCode.
What is the time complexity of LeetCode 2915. Length of the Longest Subsequence That Sums to Target?
The Python solution on this page runs in O(n\times target).
What is the space complexity of LeetCode 2915. Length of the Longest Subsequence That Sums to Target?
The Python solution on this page uses O(n\times target) auxiliary space.
What topics does LeetCode 2915. Length of the Longest Subsequence That Sums to Target cover?
LeetCode 2915. Length of the Longest Subsequence That Sums to Target is tagged Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview