Input: nums =[1,2,3,4,5], target =9Output: 3Explanation: 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 is3.
Input: nums =[4,1,3,2,1,5], target =7Output: 4Explanation: There are 5 subsequences with a sum equal to 7:[4,3],[4,1,2],[4,2,1],[1,1,5], and [1,3,2,1]. The longest subsequence is[1,3,2,1]. Hence, the answer is4.
We want the longest subsequence whose sum is exactly target. This is a variant of the subset sum problem, but instead of just checking if a sum is possible, we track the maximum length for each possible sum using dynamic programming.
classSolution {
publicintlengthOfLongestSubsequence(int[] nums, int target) {
Map<Integer, Integer> dp =new HashMap<>();
dp.put(0, 0);
for (int x : nums) {
Map<Integer, Integer> cur =new HashMap<>(dp);
for (var e : cur.entrySet()) {
int ns = e.getKey() + x;
if (ns <= target)
dp.put(ns, Math.max(dp.getOrDefault(ns, -1), e.getValue() + 1));
}
}
return dp.containsKey(target) ? dp.get(target) : -1;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funlengthOfLongestSubsequence(nums: IntArray, target: Int): Int {
val dp = mutableMapOf(0 to 0)
for (x in nums) {
val cur = dp.toMap()
for ((s, l) in cur) {
val ns = s + x
if (ns <= target)
dp[ns] = maxOf(dp.getOrDefault(ns, -1), l + 1)
}
}
return dp[target] ?: -1 }
}
1
2
3
4
5
6
7
8
9
10
classSolution:
deflengthOfLongestSubsequence(self, nums: list[int], target: int) -> int:
dp: dict[int, int] = {0: 0}
for x in nums:
cur = dp.copy()
for s, l in cur.items():
ns = s + x
if ns <= target:
dp[ns] = max(dp.get(ns, -1), l +1)
return dp.get(target, -1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnlength_of_longest_subsequence(nums: Vec<i32>, target: i32) -> i32 {
use std::collections::HashMap;
letmut dp = HashMap::new();
dp.insert(0, 0);
for&x in&nums {
let cur = dp.clone();
for (&s, &l) in&cur {
let ns = s + x;
if ns <= target {
dp.insert(ns, dp.get(&ns).copied().unwrap_or(-1).max(l +1));
}
}
}
*dp.get(&target).unwrap_or(&-1)
}
}