Leetcode 2915: Length of the Longest Subsequence That Sums to Target

grid47
grid47
Exploring patterns and algorithms
Jan 20, 2024 7 min read

You are given an array of integers nums and a target sum target. Your task is to find the length of the longest subsequence from nums that sums up to target. A subsequence can be derived by deleting some or no elements from nums while maintaining the original order of the remaining elements. If no such subsequence exists, return -1.
Problem
Approach
Steps
Complexity
Input: You are given an integer array `nums` and an integer `target`.
Example: nums = [2, 3, 5, 7], target = 10
Constraints:
• 1 <= nums.length <= 1000
• 1 <= nums[i] <= 1000
• 1 <= target <= 1000
Output: Return the length of the longest subsequence of `nums` that sums up to `target`. If no such subsequence exists, return -1.
Example: For `nums = [2, 3, 5, 7]` and `target = 10`, the output is 3.
Constraints:
Goal: To find the longest subsequence that sums up to the target, we use dynamic programming to store the length of the subsequence at each sum.
Steps:
• Create a 2D array `dp` where each entry `dp[i][j]` represents the length of the longest subsequence that sums up to `j` using the first `i` elements of `nums`.
• Initialize `dp[i][0] = 0` for all `i`, as a sum of 0 can be achieved with an empty subsequence.
• For each element `nums[i]`, update the `dp` table for all sums from `target` down to `nums[i]`. If adding `nums[i]` to a previous subsequence results in a valid subsequence, update the length.
• Return `dp[n][target]`, where `n` is the size of `nums`. If no valid subsequence exists, return -1.
Goal: The array length is guaranteed to be between 1 and 1000. The values in the array are between 1 and 1000, and the target sum is also between 1 and 1000.
Steps:
• The length of the array is between 1 and 1000.
• Each element in the array is between 1 and 1000.
• The target sum is between 1 and 1000.
Assumptions:
• The target is always a positive integer.
• The input array contains only positive integers.
Input: nums = [2, 3, 5, 7], target = 10
Explanation: One of the longest subsequences that sum to 10 is [3, 7], which has a length of 2. Another valid subsequence is [2, 3, 5], which also sums to 10 and has a length of 3. The longest subsequence is [2, 3, 5], so the answer is 3.

Input: nums = [1, 2, 3, 4], target = 6
Explanation: The subsequences that sum to 6 are [2, 4], [1, 3], and [1, 2, 3]. The longest subsequence is [1, 2, 3], which has a length of 3.

Input: nums = [1, 1, 1, 1], target = 5
Explanation: It is impossible to form a subsequence that sums to 5 since the sum of all elements is 4. Therefore, the answer is -1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus