Longest Subsequence With Limited Sum

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.

Example 1
Inputnums = [4,5,2,1], queries = [3,10,21]
Output[2,3,4]
For each query, the maximum subsequence sizes with sums at most 3, 10, and 21 are 2, 3, and 4 respectively.
Example 2
Inputnums = [2,3,4,5], queries = [1]
Output[0]
The empty subsequence is the only subsequence that has a sum less than or equal to 1, so answer[0] = 0.

Constraints

  • n == nums.length
  • m == queries.length
  • 1 <= n, m <= 1000
  • 1 <= nums[i], queries[i] <= 10^6

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate