Leetcode 2389. Longest Subsequence With Limited Sum
We are given an array of integers nums
and an array of integers queries
. For each query in queries
, we need to determine the length of the longest subsequence in nums
such that the sum of the elements in the subsequence is less than or equal to the query value.
The function signature is:
vector<int> answerQueries(vector<int>& nums, vector<int>& queries);
nums
and the values within nums
and queries
?
1 <= nums.length, queries.length <= 1000
1 <= nums[i], queries[i] <= 10^6
nums
: Sorting the array will help us consider the smallest elements first, which allows us to maximize the number of elements included in the subsequence without exceeding the query sum.nums
to easily determine how many elements can be included without exceeding each query value in queries
.#include <vector>
#include <algorithm> // For sort and lower_bound
using namespace std;
vector<int> answerQueries(vector<int>& nums, vector<int>& queries) {
// Sort the nums array to consider smallest elements first
sort(nums.begin(), nums.end());
// Compute the prefix sums of the sorted nums array
vector<int> prefixSums(nums.size(), 0);
prefixSums[0] = nums[0];
for (int i = 1; i < nums.size(); ++i) {
prefixSums[i] = prefixSums[i-1] + nums[i];
}
// Result vector to store the answer for each query
vector<int> result(queries.size(), 0);
// Process each query
for (int i = 0; i < queries.size(); ++i) {
int query = queries[i];
// Use binary search to find the maximum index where prefixSum is <= query
auto it = upper_bound(prefixSums.begin(), prefixSums.end(), query);
// Distance from the prefixSums beginning to the position found is the length
result[i] = distance(prefixSums.begin(), it);
}
return result;
}
nums
array takes (O(n \log n)), where (n) is the length of nums
.queries
.This approach ensures that we efficiently determine the longest subsequence for each query, balancing both time complexity and clarity.
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?