Longest Subsequence With Limited Sum
Using a combination of sorting, prefix sum calculation, and binary search can make the solution more efficient. Let’s dive into it:
Sorting: Sorting
nums
in ascending order helps us in quickly identifying how many elements we can include in our subsequence for a given query. This is because if a numberx
can be included in the sum, then all numbers less thanx
can also be included.Prefix sum: Calculating the prefix sum of
nums
helps us in quickly figuring out the total sum of elements from the start of the array to a given index. The prefix sum is an array where the value at indexi
is the sum of all numbers fromnums[0]
tonums[i]
.Binary Search: For each query, we can perform a binary search on the prefix sum array to find the largest index
i
such thatprefix_sum[i]
is less than or equal to the query. Thei+1
would be the maximum size of the subsequence for the query, since array indices start from 0.
Here is the code:
|
|
In this code, the nums
array is first sorted in ascending order, and then the prefix sum array is computed. For each query, a binary search is performed on the prefix sum array to find the largest index i
such that prefix_sum[i]
is less than or equal to the query. The i+1
is then appended to the result list. The result list is returned at the end.