#2389

Longest Subsequence With Limited Sum

Easy
ArrayBinary SearchGreedySortingPrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n + m log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n + m log n)Space O(n)

By sorting the `nums` array and using a prefix sum approach, we can efficiently determine the maximum size of a subsequence for each query. This method leverages the fact that smaller numbers contribute more to the sum, allowing us to maximize the size of the subsequence.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the `nums` array in ascending order.
  2. 2Step 2: Compute the prefix sums of the sorted array.
  3. 3Step 3: For each query, use binary search to find the largest index where the prefix sum is less than or equal to the query.
solution.py13 lines
1# Full working Python code
2import bisect
3
4def maxSubsequenceSize(nums, queries):
5    nums.sort()
6    prefix_sum = [0] * (len(nums) + 1)
7    for i in range(1, len(nums) + 1):
8        prefix_sum[i] = prefix_sum[i - 1] + nums[i - 1]
9    results = []
10    for query in queries:
11        max_size = bisect.bisect_right(prefix_sum, query) - 1
12        results.append(max_size)
13    return results

Complexity note: The sorting step takes O(n log n), and for each query, we perform a binary search on the prefix sums, which takes O(log n). Thus, the overall complexity is dominated by the sorting step.

  • 1Sorting the array allows for efficient sum calculations.
  • 2Using prefix sums simplifies the problem of finding valid subsequences.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.