✅ Simple Iterative DP (1-D) + Explanation || Python || 6 lines || Beats 100%✅
Approach\nThis problem is very similar to the popular Coin Change problem, so we will use the same approach to solve it.\n\n# Algorithm\nLet dp[i] represent the
# Approach\nThis problem is very similar to the popular [Coin Change](https://leetcode.com/problems/coin-change/description/) problem, so we will use the same approach to solve it.\n\n# Algorithm\nLet $$dp[i]$$ represent the length of the longest subsequence that can be obtained with a sum of $$i$$. We initialize $$dp[0]$$ to $$0$$ because a sum of $$0$$ can always be achieved with an empty subsequence. Then, we iterate through the elements in $$nums$$ and for each element $$num$$ in $$nums$$, we iterate from $$target$$ down to $$num$$. In this loop, $$dp[i]$$ is updated as the maximum of its current value and the value of $$dp[i - num] + 1$$. This means that we\'re considering whether including the current element $$num$$ in the subsequence will result in a longer subsequence with a sum of $$i$$. Finally, we return $$dp[target]$$.\n\n# Complexity\n- **Time complexity**: $$O(n*target)$$\nThe outer loop iterates through all elements in nums, which takes $$O(n)$$, where $$n$$ is the number of elements in the nums list. The inner loop iterates from $$target$$ down to $$num$$. In the worst case, it iterates from $$target$$ down to $$1$$. So, the inner loop takes $$O(target)$$ time in the worst case. Combining the outer and inner loops, the overall time complexity is $$O(n * target)$$.\n- **Space complexity**: $$O(target)$$\nThe space complexity is determined by the $$dp$$ list, which has a size of $$(target + 1)$$. Therefore, the space complexity is $$O(target)$$.\n\n# Code\n```\nclass Solution:\n    def lengthOfLongestSubsequence(self, nums: List[int], target: int) -> int:\n        dp = [-math.inf] * (target + 1)\n        dp[0] = 0\n        for num in nums:\n            for i in range(target, num - 1, -1):\n                dp[i] = max(dp[i], dp[i - num] + 1)\n        return dp[target] if dp[target] != -math.inf else -1\n                \n        \n```\n\n---\n\n## **Please upvote if you find it useful**
['Dynamic Programming', 'Python3']