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 Sum INPUT nums array: 4 5 2 1 [0] [1] [2] [3] queries array: 3 10 21 Find max subsequence size where sum <= query value Subsequence preserves relative order but can skip elements ALGORITHM STEPS 1 Sort nums ascending [4,5,2,1] --> [1,2,4,5] 2 Build prefix sum [1, 3, 7, 12] 1 3 7 12 3 Binary search each query Find rightmost pos <= query 4 Process each query q=3: prefix[1]=3 --> 2 items q=10: prefix[2]=7 --> 3 items q=21: prefix[3]=12 --> 4 items Greedy: Pick Smallest FINAL RESULT Output Array: 2 3 4 Query Results: Query 3: pick [1,2] sum=3, count=2 Query 10: pick [1,2,4] sum=7, count=3 Query 21: pick [1,2,4,5] sum=12, count=4 OK - [2,3,4] Key Insight: To maximize subsequence length with sum constraint, greedily pick smallest elements first. Sorting + prefix sum allows O(log n) binary search per query. Total: O(n log n + m log n) TutorialsPoint - Longest Subsequence With Limited Sum | Greedy Approach
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