MediumNo. 2915
Length of the Longest Subsequence That Sums to Target — LeetCode 2915 Python Solution
- Pattern
- Dynamic Programming
- Topics
- Array, 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
- Time
- O(n × target)
- Space · auxiliary
- O(n × target)
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
| No. | Problem | Difficulty |
|---|---|---|
| 2919 | Minimum Increment Operations to Make Array Beautiful | Medium |
| 2920 | Maximum Points After Collecting Coins From All Nodes | Hard |
| 0045 | Jump Game II | Medium |
| 0053 | Maximum Subarray | Medium |
| 0055 | Jump Game | Medium |
| 0063 | Unique Paths II | Medium |
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 × 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 × 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.