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.
1using System;
2using System.Linq;
3
4public class Solution {
5 public int[] AnswerQueries(int[] nums, int[] queries) {
6 Array.Sort(nums);
7 int[] prefixSum = new int[nums.Length];
8 prefixSum[0] = nums[0];
9 for (int i = 1; i < nums.Length; i++) {
10 prefixSum[i] = prefixSum[i - 1] + nums[i];
11 }
12
13 int[] answer = new int[queries.Length];
14 for (int i = 0; i < queries.Length; i++) {
15 int count = Array.FindLastIndex(prefixSum, x => x <= queries[i]) + 1;
16 answer[i] = count;
17 }
18 return answer;
19 }
20}
In C#, we use Array.FindLastIndex
to locate the last valid index in the prefix sum that meets the query criterion. This seamlessly provides the desired 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
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.