Longest Subsequence With Limited Sum - 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].

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.

Input & Output

Example 1 — Basic Multiple Queries
$ Input: nums = [4,5,2,1], queries = [3,10,21]
Output: [2,3,4]
💡 Note: For query 3: best subsequence is [2,1] with sum=3, count=2. For query 10: best is [4,2,1] or [5,2,1] with sum≤10, count=3. For query 21: all elements [4,5,2,1] sum=12≤21, count=4.
Example 2 — Single Element Array
$ Input: nums = [2], queries = [1,3]
Output: [0,1]
💡 Note: For query 1: element 2>1, so no elements fit, count=0. For query 3: element 2≤3, so one element fits, count=1.
Example 3 — Small Query Limits
$ Input: nums = [10,20,30], queries = [5,15,25]
Output: [0,1,1]
💡 Note: For query 5: no elements ≤5, count=0. For query 15: only 10≤15, count=1. For query 25: only 10≤25 (since 10+20=30>25), count=1.

Constraints

  • 1 ≤ nums.length, queries.length ≤ 1000
  • 1 ≤ nums[i], queries[i] ≤ 106

Visualization

Tap to expand
Longest Subsequence With Limited Sumnums = [4,5,2,1]4521queries = [3,10,21]31021Strategy: Sort nums, pick smallest firstSorted: [1,2,4,5]1245Query Results:query=3: pick [1,2] → count=2query=10: pick [1,2,4] → count=3query=21: pick [1,2,4,5] → count=4Output: [2,3,4]
Understanding the Visualization
1
Input Arrays
Given nums array and multiple query limits
2
Greedy Strategy
Sort and pick smallest elements to maximize count within limit
3
Multiple Queries
Answer each query efficiently using sorted order
Key Takeaway
🎯 Key Insight: To maximize count with limited sum, always pick the smallest available elements first using greedy strategy
Asked in
Amazon 12 Google 8 Microsoft 6
26.8K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen