You are given an integer array nums
of length n
, and an integer array queries
of length m
. For each queries[i]
, find the maximum length of a subsequence that can be obtained from nums
such that the sum of the subsequence’s elements does not exceed queries[i]
.
Return an array answer
of length m
where answer[i]
is the answer to the i-th
query.
nums
contain negative numbers?
nums
only contains non-negative integers.nums
be zero?
nums
can be zeros.nums
and queries
?
1 <= nums.length, queries.length <= 1000
0 <= nums[i], queries[i] <= 10^6
Given the constraints, we can utilize sorting and prefix sums to efficiently determine the maximum length of the subsequence for each query.
nums
array: By sorting, we can easily find the smallest elements to include in the subsequence to keep the sum under the given limit.nums
array. The prefix sums will help us quickly determine how many elements we can include for a given sum.from bisect import bisect_right
def answerQueries(nums, queries):
# Sort the numbers to make subsequence selection easier
nums.sort()
# Compute the prefix sums of the sorted nums
prefix_sums = []
current_sum = 0
for num in nums:
current_sum += num
prefix_sums.append(current_sum)
answers = []
for query in queries:
# Find the maximum length subsequence with sum <= query
pos = bisect_right(prefix_sums, query)
answers.append(pos)
return answers
# Example usage
nums = [4, 5, 2, 1]
queries = [3, 10, 21]
print(answerQueries(nums, queries)) # Output: [2, 3, 4]
nums
: O(n log n)
O(n)
O(m log n)
Overall time complexity: O(n log n + m log n)
, where n
is the length of nums
and m
is the length of queries
. Given the constraints, this approach will be efficient and suitable.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?