#2915

Length of the Longest Subsequence That Sums to Target

Medium
ArrayDynamic ProgrammingDynamic ProgrammingSubset Sum Problem
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * target)
Space
O(1)
O(target)
💡

Intuition

Time O(n * target)Space O(target)

Using dynamic programming allows us to build up solutions to subproblems, efficiently tracking the longest subsequence that sums to the target.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP array where dp[j] holds the maximum length of subsequence that sums to j.
  2. 2Step 2: Iterate through each number in nums, updating the DP array from the back to avoid overwriting results from the same iteration.
  3. 3Step 3: Return dp[target] if it's greater than 0; otherwise, return -1.
solution.py10 lines
1# Full working Python code
2
3def longest_subsequence(nums, target):
4    dp = [-1] * (target + 1)
5    dp[0] = 0
6    for num in nums:
7        for j in range(target, num - 1, -1):
8            if dp[j - num] != -1:
9                dp[j] = max(dp[j], dp[j - num] + 1)
10    return dp[target] if dp[target] != -1 else -1

Complexity note: The time complexity is O(n * target) because we iterate through each number and update the DP array for each possible sum up to the target.

  • 1Dynamic programming helps in breaking down the problem into manageable subproblems.
  • 2Understanding how to manipulate the DP array is crucial for optimizing the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.