Longest Subsequence With Limited Sum
Real-world version: Parcels Within Each AllowanceThe statement here is our own: the same inputs, outputs and technique.
Parcel weights are given as nums, and each entry of queries is a weight allowance.
For each allowance, work out the largest number of parcels that can be chosen so their weights total at most that allowance. Parcels may be chosen from anywhere in the list.
Return those counts, one per allowance, in the order the allowances are given.
Examples
Example 1
- Input
- nums = [17, 4, 23, 9], queries = [30, 4, 3, 53]
- Output
- [3, 1, 0, 4]
Sorted, the weights run 4, 9, 17, 23 with running totals 4, 13, 30, 53. An allowance of 30 reaches three parcels, one of 4 reaches one, one of 3 reaches none, and one of 53 takes all four.
Example 2
- Input
- nums = [1, 1, 1, 1, 1], queries = [1, 2, 3, 4, 5, 6]
- Output
- [1, 2, 3, 4, 5, 5]
Every parcel weighs one, so each allowance fits that many parcels, capped at the five available.
Example 3
- Input
- nums = [100, 200, 300], queries = [50]
- Output
- [0]
Even the lightest parcel is over the allowance, so none fit.
Constraints
- 1 <= nums.length <= 1000
- 1 <= queries.length <= 1000
- 1 <= nums[i] <= 10^6
- 1 <= queries[i] <= 10^6
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def answer_queries(nums: list[int], queries: list[int]) -> list[int]:public int[] answerQueries(int[] nums, int[] queries)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Frequency of the Most Frequent ElementReal-world version: Plates at One ThicknessMedium
- Maximum Coins From K Consecutive BagsReal-world version: Richest Run of Consecutive BinsMedium
- Minimum Cost to Make Array EqualReal-world version: Regrading the Survey PegsHard
- Earliest Finish Time for Land and Water Rides IReal-world version: Forge and Kiln BookingEasy