Problem Description
Given an array of positive integers nums and an integer target, return the length of the longest subsequence of nums whose elements sum exactly to target. If no such subsequence exists, return -1.
Key Insights
- The problem is a variant of the classic subset sum problem.
- Since all numbers are positive, dynamic programming can be effectively used.
- Instead of tracking whether a sum is achievable, we need to track the maximum length used to form that sum.
- Iterate through the nums and update a dp table for sums from target down to the current number to ensure each element is used at most once.
Space and Time Complexity
Time Complexity: O(n * target) where n is the length of nums. Space Complexity: O(target) for the dp array.
Solution
We use dynamic programming with a one-dimensional dp array where dp[j] represents the maximum length of a subsequence that sums to j. Initialize dp[0] to 0 (zero elements yield sum 0) and others to a very small number (or a flag value to indicate not achievable). Then, for each number in the nums array, update the dp table in reverse order (from target down to the current number) to avoid reusing the same element. After processing, if dp[target] remains at initialization value, no valid subsequence exists and return -1; otherwise, dp[target] gives the length of the longest subsequence.