Longest Subsequence With Limited Sum (LeetCode 2389): Solution and Explanation
For each query, find the most elements of nums you can pick so that their sum stays at most the query. With nums = [4,5,2,1] and queries = [3,10,21] the answer is [2,3,4].
Intuition
A subsequence keeps the original order, but a sum does not care about order. So the question is really about subsets: how many values can you pick with total at most q?
To pick as many as possible under a budget, always pick the cheapest ones. Swapping any chosen value for a smaller unchosen one never raises the total, so some optimal set is always the k smallest values.
After sorting, the cost of the k smallest values is a prefix sum. Prefix sums of positive numbers only grow, so the answer to a query is the number of prefix sums that are at most q.
Counting values <= q in a sorted array is an upper-bound binary search, which answers each query in O(log n).
Approach: Sort, prefix sums, binary search per query
- Sort
numsin increasing order. - Build
prefix, whereprefix[i]is the sum of the firsti + 1sorted values. - For each query
q, binary search withlo = 0,hi = n: ifprefix[mid] <= qsetlo = mid + 1, elsehi = mid. lois the number of prefix sums within budget; append it to the answer.
Step-by-step example
nums = [4,5,2,1], queries = [3,10,21]
- Sort nums to [1, 2, 4, 5]. The prefix sums are [1, 3, 7, 12].
- q = 3: mid = 2 has prefix 7 > 3, so hi = 2. mid = 1 has prefix 3 <= 3, so lo = 2. Answer 2.
- q = 10: mid = 2 has prefix 7 <= 10, so lo = 3. mid = 3 has prefix 12 > 10, so hi = 3. Answer 3.
- q = 21: every prefix sum is at most 21, so lo moves to 4. Answer 4.
- Return [2, 3, 4].
Code: Python, Java, C++
1class Solution:
2 def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
3 nums.sort()
4 prefix = []
5 total = 0
6 for x in nums:
7 total += x
8 prefix.append(total)
9 answer = []
10 for q in queries:
11 lo, hi = 0, len(prefix)
12 while lo < hi:
13 mid = (lo + hi) // 2
14 if prefix[mid] <= q:
15 lo = mid + 1
16 else:
17 hi = mid
18 answer.append(lo)
19 return answer1class Solution {
2 public int[] answerQueries(int[] nums, int[] queries) {
3 Arrays.sort(nums);
4 int n = nums.length;
5 long[] prefix = new long[n];
6 long total = 0;
7 for (int i = 0; i < n; i++) {
8 total += nums[i];
9 prefix[i] = total;
10 }
11 int[] answer = new int[queries.length];
12 for (int k = 0; k < queries.length; k++) {
13 int q = queries[k];
14 int lo = 0, hi = n;
15 while (lo < hi) {
16 int mid = (lo + hi) / 2;
17 if (prefix[mid] <= q) {
18 lo = mid + 1;
19 } else {
20 hi = mid;
21 }
22 }
23 answer[k] = lo;
24 }
25 return answer;
26 }
27}1class Solution {
2public:
3 vector<int> answerQueries(vector<int>& nums, vector<int>& queries) {
4 sort(nums.begin(), nums.end());
5 int n = nums.size();
6 vector<long long> prefix(n);
7 long long total = 0;
8 for (int i = 0; i < n; i++) {
9 total += nums[i];
10 prefix[i] = total;
11 }
12 vector<int> answer;
13 for (int q : queries) {
14 int lo = 0, hi = n;
15 while (lo < hi) {
16 int mid = (lo + hi) / 2;
17 if (prefix[mid] <= q) {
18 lo = mid + 1;
19 } else {
20 hi = mid;
21 }
22 }
23 answer.push_back(lo);
24 }
25 return answer;
26 }
27};Time and space complexity
O((n + m) log n)
Sorting is O(n log n), the prefix pass is O(n), and each of the m queries does one O(log n) binary search.
O(n)
The prefix array holds n sums; the answer array is the required output.
Other approaches
Greedy scan per query (time O(n log n + n * m), space O(1))
After sorting, walk the sorted values for each query and stop when the running sum passes q. Simple and fast enough for 1000 by 1000.
Sort the queries offline (time O(n log n + m log m), space O(m))
Sort query indices by value and sweep one pointer through the prefix sums, since a larger budget never fits fewer values.
Common mistakes
- Searching for the first prefix sum that is >= q instead of > q. A prefix exactly equal to the budget still fits.
- Thinking the subsequence must stay contiguous or keep order in a way that matters. Only the chosen set matters for the sum.
- Returning the index of the last fitting prefix instead of the count. The count is that index plus one, which is exactly where the upper-bound search stops.
Frequently asked questions
Why is sorting allowed when the problem talks about subsequences?
Any set of positions forms a valid subsequence, and its sum does not depend on order. So choosing which values to keep is all that matters, and sorting just makes the cheapest choice easy to find.
Can a prefix sum overflow?
At most 1000 values of 10^6 add up to 10^9, which fits in a 32-bit int, but using a 64-bit prefix array costs nothing and avoids worry.
What if a query is smaller than every value?
The first prefix sum already exceeds it, the search ends with lo = 0, and the answer for that query is 0.