Longest Subsequence With Limited Sum - Problem
Find the Maximum Subsequence Size Within Budget Constraints

You're given an integer array nums of length n and an array of queries of length m. For each query value, you need to determine the maximum number of elements you can select from nums such that their sum doesn't exceed the query limit.

Key Points:
• You can pick any elements from nums (order doesn't matter)
• The sum of selected elements must be ≤ query value
• You want to maximize the count of elements, not their sum
• Return an array where answer[i] is the maximum subsequence size for queries[i]

Example: If nums = [4,5,2,1] and queries = [3,10,21], then:
• Query 3: Can pick [2,1] → answer is 2
• Query 10: Can pick [4,5,1] or [2,1,4,5] but [2,1,4] gives us 3 elements → answer is 3
• Query 21: Can pick all [4,5,2,1] → answer is 4

Input & Output

example_1.py — Basic Case
$ Input: nums = [4,5,2,1], queries = [3,10,21]
Output: [2,3,4]
💡 Note: For query 3: Best is [2,1] with sum=3, giving 2 elements. For query 10: Best is [1,2,4] with sum=7, giving 3 elements. For query 21: Can take all [1,2,4,5] with sum=12, giving 4 elements.
example_2.py — Single Element
$ Input: nums = [2,3,4,5], queries = [1]
Output: [0]
💡 Note: Query 1 is less than the smallest element (2), so we cannot take any elements. Answer is 0.
example_3.py — Large Budget
$ Input: nums = [1,2,3], queries = [100]
Output: [3]
💡 Note: Query 100 is much larger than the sum of all elements (1+2+3=6), so we can take all 3 elements.

Constraints

  • 1 ≤ nums.length, queries.length ≤ 103
  • 1 ≤ nums[i], queries[i] ≤ 106
  • Goal: Maximize the count of elements, not their sum

Visualization

Tap to expand
Shopping Strategy: Buy Maximum ItemsItems: [🎮$4, 📚$5, ☕$2, 🍎$1] Budget: $10Step 1: Sort by price (cheapest first)🍎$1$2🎮$4📚$5Step 2: Calculate running costs🍎$1 total🍎☕$3 total🍎☕🎮$7 total🍎☕🎮📚$12 totalStep 3: Binary search finds we can afford 3 items (total $7 ≤ $10)Maximum: 3 items for $10
Understanding the Visualization
1
Sort by Price
Arrange all items from cheapest to most expensive
2
Running Totals
Keep track of cumulative costs as you add cheaper items
3
Find Budget Limit
For each budget, binary search to find how many cheapest items you can afford
Key Takeaway
🎯 Key Insight: Greedy approach works perfectly here - always choose the smallest elements first to maximize count within budget constraints.
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 5
24.5K 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