Longest Subsequence With Limited Sum

Sort, prefix-sum, then upper_bound each query to find how many small items fit under the cap.

Easy
Time O((n + q) log n) Space O(n)
LeetCode
4 min read
sorting prefix-sum binary-search greedy

Problem#

For each query, return the maximum length of a subsequence of nums whose sum is at most the query.

Examples#

  • nums = [4,5,2,1], queries = [3,10,21][2,3,4]
  • nums = [2,3,4,5], queries = [1][0]

Constraints#

  • n == nums.length, m == queries.length, 1 <= n, m <= 1000, 1 <= nums[i] <= 10^6, 1 <= queries[i] <= 10^9.

Approach#

Greedy: smaller numbers fit more. Sort nums ascending, build prefix sums, then for each query find the largest prefix length whose sum does not exceed the query via upper_bound.

Solution#

Longest Subsequence With Limited Sum
class Solution {
public:
vector<int> answerQueries(vector<int>& nums, vector<int>& queries) {
sort(nums.begin(), nums.end());
int n = nums.size();
vector<long long> pref(n + 1, 0);
for (int i = 0; i < n; ++i) pref[i + 1] = pref[i] + nums[i];
vector<int> ans;
ans.reserve(queries.size());
for (int q : queries) {
int k = upper_bound(pref.begin(), pref.end(), (long long)q) - pref.begin() - 1;
ans.push_back(k);
}
return ans;
}
};

Editorial#

Picking the smallest available elements is always optimal for maximizing count. upper_bound on the prefix-sum array returns the first prefix that exceeds the query; subtracting one gives the maximum admissible length.

Complexity#

  • Time: O((n + q) log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.