Longest Subsequence With Limited Sum — LeetCode 2389 Python Solution
- Problem
- #2389
- Pattern
- Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O((n + m) \times \log n) |
| Space | O(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.