#2389
Easy Algorithms Longest subsequence with limited sum
Array Binary Search Greedy Sorting Prefix Sum
73.4% acceptance
Feb 25, 2026
2128
198
You are given an integer array nums of length n, and an integer array queries of length m.
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].
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.
Solution
Rust
Time O(n log n)
Space O(n)
impl Solution {
pub fn answer_queries(mut nums: Vec<i32>, queries: Vec<i32>) -> Vec<i32> {
nums.sort_unstable();
let mut prefix = vec![0i64];
for &n in &nums { prefix.push(prefix.last().unwrap() + n as i64); }
queries.iter().map(|&q| {
prefix.partition_point(|&p| p <= q as i64) as i32 - 1
}).collect()
}
}