Longest Subsequence With Limited Sum — LeetCode 2389 Python Solution

EasyGreedyArrayBinary SearchPrefix SumSorting
Problem
#2389
Pattern
Prefix Sum
Reading time
2 min

The problem

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].

Example

Input
nums = [4,5,2,1], queries = [3,10,21]
Output
[2,3,4]
Explanation
We answer the queries as follows:

Python solution

Python
class Solution:
    def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
        nums.sort()
        s = list(accumulate(nums))
        return [bisect_right(s, q) for q in queries]

Complexity

MeasureComplexity
TimeO((n + m) \times \log n)
SpaceO(n) or O(\log n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2389. Longest Subsequence With Limited Sum is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2389. Longest Subsequence With Limited Sum?
LeetCode 2389. Longest Subsequence With Limited Sum is rated Easy on LeetCode.
What topics does LeetCode 2389. Longest Subsequence With Limited Sum cover?
LeetCode 2389. Longest Subsequence With Limited Sum is tagged Greedy, Array, Binary Search, Prefix Sum and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview