Problem Description
Given an integer array nums and an integer array queries, return an array answer where answer[i] is the maximum size of a subsequence that can be taken from nums such that the sum of its elements is less than or equal to queries[i]. A subsequence is an array derived from another array by deleting some or no elements without changing the order of the remaining elements.
Key Insights
- Sorting nums allows us to include the smallest elements first, maximizing the subsequence size.
- Building a prefix sum array from the sorted nums helps quickly determine the sum of the smallest k elements.
- Binary search on the prefix sum array efficiently finds the maximum number of elements that can sum up to a given query value.
- Combining sorting (O(n log n)) and binary search for each query (O(m log n)) results in an efficient solution.
Space and Time Complexity
Time Complexity: O(n log n + m log n)
Space Complexity: O(n) for the prefix sum array
Solution
First, sort the nums array to have the smallest elements at the beginning. Next, compute a prefix sum array where each entry represents the cumulative sum of the smallest elements up to that index. For each query, use binary search on the prefix sum array to find the largest index where the cumulative sum is less than or equal to the query value. This index corresponds to the maximum size of the subsequence that fits within the query sum.