File: longest-subsequence-with-limited-sum/solution.py

Date: 2026-06-06

Time: 17:28

Purpose

This file solves LeetCode 2389: Longest Subsequence With Limited Sum. Given an array nums and an array queries, for each query it finds the maximum number of elements you can pick from nums (in any order, non-contiguous) such that their sum doesn't exceed the query value.

It's one solution module in a large repository of LeetCode solutions, each following the same directory convention: problem-slug/solution.py.

Key Components

maxSizeSubsequenceSumQueries(nums, queries) — the sole public function. Takes the input arrays and returns a list of answers, one per query.

Patterns

The solution uses a greedy + prefix sum + binary search pattern, which is the canonical O(n log n + m log n) approach for this problem class:

1. Greedy sort: To maximize the count of elements fitting under a sum budget, always pick the smallest elements first. Sorting enables this.

2. Prefix sum via accumulate: After sorting, prefix[i] is the minimum possible sum when picking i+1 elements.

3. Binary search via bisectright: For each query q, bisectright(prefix, q) returns how many elements fit — the position where q would be inserted, which equals the count of prefix sums ≤ q.

The entire solution is a one-liner pipeline after building the prefix array, which is idiomatic Python for this kind of problem.

Dependencies

Imports:

Imported by: The test_solution.py in the same directory, plus the "Imported By" list in the prompt appears to be a test-runner artifact listing all test files in the repo (likely from a shared test harness that discovers solution modules).

Flow


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

1. sorted(nums)        → [1, 2, 4, 5]
2. accumulate(...)     → [1, 3, 7, 12]     (prefix sums)
3. bisect_right(_, 3)  → 2                  (elements 1,2 fit under 3)
   bisect_right(_, 10) → 3                  (elements 1,2,4 fit under 10)
   bisect_right(_, 21) → 4                  (all 4 elements fit under 21)

result: [2, 3, 4]

Each query is independent — the prefix array is built once, then each query is a O(log n) binary search.

Invariants

Error Handling

None. The function assumes valid inputs per LeetCode constraints (non-empty arrays, positive integers). No bounds checking or exception handling — appropriate for a competitive programming solution.

Topics to Explore

Beliefs