Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
You are given an integer array nums
of length n
, and an integer array queries
of length m
.
Return an array answer
of length m
where answer[i]
is the maximum size of a subsequence that you can take from nums
such that the sum of its elements is less than or equal to queries[i]
.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: nums = [4,5,2,1], queries = [3,10,21]
Output: [2,3,4]
Explanation: We answer the queries as follows:
- The subsequence [2,1] has a sum less than or equal to 3. It can be proven that 2 is the maximum size of such a subsequence, so answer[0] = 2.
- The subsequence [4,5,1] has a sum less than or equal to 10. It can be proven that 3 is the maximum size of such a subsequence, so answer[1] = 3.
- The subsequence [4,5,2,1] has a sum less than or equal to 21. It can be proven that 4 is the maximum size of such a subsequence, so answer[2] = 4.
Example 2:
Input: nums = [2,3,4,5], queries = [1]
Output: [0]
Explanation: The empty subsequence is the only subsequence that has a sum less than or equal to 1, so answer[0] = 0.
Constraints:
n == nums.length
m == queries.length
1 <= n, m <= 1000
1 <= nums[i], queries[i] <= 106
public int[] answerQueries(int[] nums, int[] queries) {
Arrays.sort(nums);
Arrays.parallelPrefix(nums, Integer::sum);
for (int i = 0; i < queries.length; ++i) {
int pos = Arrays.binarySearch(nums, queries[i] + 1);
queries[i] = pos < 0 ? ~pos : pos;
}
return queries;
}
vector<int> answerQueries(vector<int>& nums, vector<int>& queries) {
sort(begin(nums), end(nums));
partial_sum(begin(nums), end(nums), begin(nums));
transform(begin(queries), end(queries), begin(queries), [&](int q){
return upper_bound(begin(nums), end(nums), q) - begin(nums);
});
return queries;
}
class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
numsSorted = sorted(nums)
res = []
for q in queries:
total = 0
count = 0
for num in numsSorted:
total += num
count += 1
if total > q:
count -= 1
break
res.append(count)
return res
In our experience, we suggest you solve this Longest Subsequence With Limited Sum LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Longest Subsequence With Limited Sum LeetCode Solution
I hope this Longest Subsequence With Limited Sum LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>