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.
思路:(排序 + 前缀和 + upper_bound)
对nums进行从小到大排序 (因为从小的数开始取 才会最长)然后求前缀和 遍历queries数组 找前缀和中第一个大于q的数的地址(利用upper_bound函数), 该地址减去 前缀和的初始地址 就是最大长度
相关algorithm库函数用法如下
代码:
class Solution {
public:
vector<int> answerQueries(vector<int>& nums, vector<int>& queries) {
sort(nums.begin(), nums.end());
vector<int> res;
int j = 0;
vector<int> presum(nums.size());
presum[0] = nums[0];
for(int i = 1; i < nums.size(); i++) {
presum[i] = presum[i - 1] + nums[i];
}
for(auto q: queries) {
res.push_back(upper_bound(presum.begin(), presum.end(), q) - presum.begin());
}
return res;
}
};