KatInterview

Maximum Affordable Items Within Budget

Greedy & IntervalsAuto-graded · 21 test cases
EasyAuto-gradedGreedy & Intervalsgreedysortingarrays

Last updated

Determine the maximum collection of items that can be purchased given individual item costs and a total spending limit.

You are given a non-negative integer target amount representing your available funds, alongside a list of item costs. Each entry in the cost list corresponds to a single available item.

Write a function that calculates the largest number of items you can buy without spending more than the available budget. Return the individual costs of all purchased items sorted in non-decreasing order.

If there are multiple combinations that achieve the maximum item count, choose the combination with the smallest total spending. If a tie still remains, any valid set of item prices is acceptable as long as it is returned in sorted order.

Constraints

  • 0 <= budget <= 10^9
  • 0 <= len(prices) <= 10^5
  • 0 <= prices[i] <= 10^9 for all 0 <= i < len(prices)

Examples

Example 1

Input: max_distinct_purchases(50, [20, 10, 30, 15, 5])

Output: [5, 10, 15, 20]

Example 2

Input: max_distinct_purchases(10, [6, 4, 3, 2])

Output: [2, 3, 4]

Example 3

Input: max_distinct_purchases(5, [5, 5, 1])

Output: [1]

Hints

Hint 1

Consider how picking cheaper items affects your remaining budget compared to picking more expensive items.

Hint 2

Sorting the list of item costs beforehand makes it straightforward to process items in order of increasing cost.

Hint 3

Iterate through the sorted costs, keeping a running total until adding another item would exceed the budget.