2389. Longest Subsequence With Limited Sum Easy

@problem@discussion
#Array#Binary Search#Greedy#Sorting#Prefix Sum



1/**
2 * [2389] Longest Subsequence With Limited Sum
3 *
4 * You are given an integer array nums of length n, and an integer array queries of length m.
5 * Return an array answer of length m where answer[i] is the maximum size of a subsequence that you can take from nums such that the sum of its elements is less than or equal to queries[i].
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 * Example 1:
9 * 
10 * Input: nums = [4,5,2,1], queries = [3,10,21]
11 * Output: [2,3,4]
12 * Explanation: We answer the queries as follows:
13 * - The subsequence [2,1] has a sum less than or equal to 3. It can be proven that 2 is the maximum size of such a subsequence, so answer[0] = 2.
14 * - The subsequence [4,5,1] has a sum less than or equal to 10. It can be proven that 3 is the maximum size of such a subsequence, so answer[1] = 3.
15 * - The subsequence [4,5,2,1] has a sum less than or equal to 21. It can be proven that 4 is the maximum size of such a subsequence, so answer[2] = 4.
16 * 
17 * Example 2:
18 * 
19 * Input: nums = [2,3,4,5], queries = [1]
20 * Output: [0]
21 * Explanation: The empty subsequence is the only subsequence that has a sum less than or equal to 1, so answer[0] = 0.
22 *  
23 * Constraints:
24 * 
25 * 	n == nums.length
26 * 	m == queries.length
27 * 	1 <= n, m <= 1000
28 * 	1 <= nums[i], queries[i] <= 10^6
29 * 
30 */
31pub struct Solution {}
32
33// problem: https://leetcode.com/problems/longest-subsequence-with-limited-sum/
34// discuss: https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/?currentPage=1&orderBy=most_votes&query=
35
36// submission codes start here
37
38impl Solution {
39    pub fn answer_queries(nums: Vec<i32>, queries: Vec<i32>) -> Vec<i32> {
40        vec![]
41    }
42}
43
44// submission codes end
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49
50    #[test]
51    fn test_2389() {
52    }
53}
54


Back
© 2025 bowen.ge All Rights Reserved.