Sponsored
Sponsored
By sorting the nums
array, the subsequences with the smallest sums can be easily constructed. Calculating a prefix sum for the sorted array helps in determining how many elements can be included before the sum exceeds the query limit.
Time Complexity: O(n log n + m * n), where n is the length of nums
and m is the length of queries
.
Space Complexity: O(n) for the prefix sum array.
1var answerQueries = function(nums, queries) {
2 nums.sort((a, b) => a - b);
3 for(let i = 1; i < nums.length; i++) {
4 nums[i] += nums[i - 1];
5 }
6
7 return queries.map(q => {
8 let count = 0;
9 for(let sum of nums){
10 if(sum <= q){
11 count++;
12 } else {
13 break;
14 }
15 }
16 return count;
17 });
18};
JavaScript uses Array.sort
to sort the numbers and computes prefix sums in place. For each query, it iterates through the prefix sums to find the largest feasible subsequence size.
This approach extends the prefix sum method by using binary search to efficiently find where the query fits within the prefix sum array. This reduces the time complexity significantly, especially for large inputs.
Time Complexity: O(n log n + m log n), where n is the length of nums
and m is the length of queries
.
Space Complexity: O(n) for the prefix sum array.
The JavaScript solution uses an in-place binary search on the prefix sums to find the largest number of elements that can fit for each query value, optimizing the search process significantly compared to linear iteration.