Length of the Longest Subsequence That Sums to Target — LeetCode 2915 Python Solution
- Problem
- #2915
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n\times target) |
| Space | O(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.