Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 2389. Longest Subsequence With Limited Sum

Rain Hu

2389. Longest Subsequence With Limited Sum


一、題目

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:

Example 2:

Constraints:


二、分析

三、解題

vector<int> answerQueries(vector<int>& nums, vector<int>& queries) {
    sort(nums.begin(), nums.end()); // 排序
    vector<int> acc;
    vector<int> res;
    for (int x : nums) {            // 求 prefix sum
        if (acc.empty())
            acc.push_back(x);
        else
            acc.push_back(acc.back() + x);
    }
    for (const auto& q : queries) { // 用 binary search 求解
        res.push_back(distance(acc.begin(), upper_bound(acc.begin(), acc.end(), q)));
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 2279. Maximum Bags With Full Capacity of Rocks
Next
[LeetCode] 790. Domino and Tromino Tiling