【排序 + 前缀和 + 二分】 首先子序列和顺序无关,要想让元素个数多就应该尽量先找小的元素。因此可以先把元素排序,然后计算前缀和与queries比较,找到第一个小于等于queries[i]的元素即可。
class Solution {
public int binary(int[] arr, int k) {
int l = 0, r = arr.length - 1, n = arr.length;
while (l <= r) {
int m = (l + r) >> 1;
if (arr[m] > k) r = m - 1;
else l = m + 1;
}
return r;
}
public int[] answerQueries(int[] nums, int[] queries) {
int n = nums.length, sum = 0;
Arrays.sort(nums);
for (int i = 0; i < n; i++) {
sum += nums[i];
nums[i] = sum;
}
for (int i = 0; i < queries.length; i++) {
queries[i] = binary(nums, queries[i]) + 1;
}
return queries;
}
}