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.
1import java.util.Arrays;
2
3public class Solution {
4 public int[] answerQueries(int[] nums, int[] queries) {
5 Arrays.sort(nums);
6 int[] prefixSum = new int[nums.length];
7 prefixSum[0] = nums[0];
8 for (int i = 1; i < nums.length; i++) {
9 prefixSum[i] = prefixSum[i - 1] + nums[i];
10 }
11
12 int[] answer = new int[queries.length];
13 for (int i = 0; i < queries.length; i++) {
14 int count = 0;
15 for (int j = 0; j < nums.length; j++) {
16 if (prefixSum[j] <= queries[i]) {
17 count = j + 1;
18 } else {
19 break;
20 }
21 }
22 answer[i] = count;
23 }
24 return answer;
25 }
26}
This Java solution follows the same logic as in other languages; it sorts the nums
list and constructs prefix sums. It iteratively checks each query against the prefix sums to determine the maximum 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.
1
This C code implements binary search on the prefix sum array to quickly determine how many elements from the sorted array have a sum that fits within the query limit. This is more efficient than iterating linearly.