[LeetCode] Longest Subsequence With Limited Sum

2389. Longest Subsequence With Limited Sum

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
vector<int> answerQueries(vector<int>& A, vector<int>& Q) {
sort(begin(A), end(A));
vector<long long> psum {0};
for(auto& a : A) psum.push_back(psum.back() + a);
vector<int> res;
for(auto& q : Q) {
auto now = upper_bound(begin(psum),end(psum), q) - begin(psum);
res.push_back(now - 1);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/28/PS/LeetCode/longest-subsequence-with-limited-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.