2915. Length of the Longest Subsequence That Sums to Target Medium

@problem@discussion
#Array#Dynamic Programming



1/**
2 * [2915] Length of the Longest Subsequence That Sums to Target
3 *
4 * You are given a 0-indexed array of integers nums, and an integer target.
5 * Return the length of the longest subsequence of nums that sums up to target. If no such subsequence exists, return -1.
6 * A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
7 *  
8 * <strong class="example">Example 1:
9 * 
10 * Input: nums = [1,2,3,4,5], target = 9
11 * Output: 3
12 * Explanation: 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 is 3.
13 * 
14 * <strong class="example">Example 2:
15 * 
16 * Input: nums = [4,1,3,2,1,5], target = 7
17 * Output: 4
18 * Explanation: 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 is 4.
19 * 
20 * <strong class="example">Example 3:
21 * 
22 * Input: nums = [1,1,5,4,5], target = 3
23 * Output: -1
24 * Explanation: It can be shown that nums has no subsequence that sums up to 3.
25 * 
26 *  
27 * Constraints:
28 * 
29 * 	1 <= nums.length <= 1000
30 * 	1 <= nums[i] <= 1000
31 * 	1 <= target <= 1000
32 * 
33 */
34pub struct Solution {}
35
36// problem: https://leetcode.com/problems/length-of-the-longest-subsequence-that-sums-to-target/
37// discuss: https://leetcode.com/problems/length-of-the-longest-subsequence-that-sums-to-target/discuss/?currentPage=1&orderBy=most_votes&query=
38
39// submission codes start here
40
41impl Solution {
42    pub fn length_of_longest_subsequence(nums: Vec<i32>, target: i32) -> i32 {
43        0
44    }
45}
46
47// submission codes end
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52
53    #[test]
54    fn test_2915() {
55    }
56}
57


Back
© 2025 bowen.ge All Rights Reserved.