KatInterview

Budget Growth Through Threshold-Locked Ventures

Heaps, Sorting & SearchAuto-graded · 21 test cases
MediumAuto-gradedHeaps, Sorting & Searchgreedyheapsorting

Last updated

Greedy plus min-sorted unlocking and a max-heap: pick up to k ventures, each requiring a minimum budget, to maximize the final budget.

You manage a budget that starts at start_budget. There are n ventures, numbered from 0 to n - 1. Venture i has a minimum budget requirement required[i] and a payout gain[i].

You may carry out ventures one at a time, in any order you choose, and each venture can be done at most once. Venture i can be started only when your current budget is at least required[i]. Starting a venture does not spend any of your budget. When it finishes, your budget grows by gain[i].

You may carry out at most max_ventures ventures (including zero). Return the largest budget you can end up with.

Details

  • Payouts are non-negative. Skipping a venture is always allowed, so you are never forced to take one.
  • If max_ventures is 0, or no venture is affordable at the start, the answer is simply start_budget.
  • If max_ventures exceeds the number of ventures, you can still do at most n of them.
  • Several ventures may share the same requirement or the same payout.

Function

Implement max_final_budget(max_ventures, start_budget, gain, required), where:

  • max_ventures is the maximum number of ventures allowed,
  • start_budget is the initial budget,
  • gain is the list of payouts,
  • required is the list of minimum budgets, aligned with gain by index.

Return a single integer: the maximum final budget.

Constraints

  • 0 <= max_ventures <= 10^9
  • 0 <= start_budget <= 10^9
  • 1 <= n <= 2 * 10^5, where n = len(gain) = len(required)
  • 0 <= gain[i] <= 10^9
  • 0 <= required[i] <= 10^9
  • The solution should run in roughly O(n log n) time.

Examples

Example 1

Input: max_final_budget(2, 0, [1, 2, 3], [0, 1, 1])

Output: 4

Example 2

Input: max_final_budget(3, 0, [1, 2, 3], [0, 1, 2])

Output: 6

Example 3

Input: max_final_budget(3, 5, [1, 2], [10, 20])

Output: 5

Hints

Hint 1

Funds never go down, so once a venture becomes affordable it stays affordable. Think about which affordable venture is always the best one to take next.

Hint 2

Sort ventures by required budget and keep a pointer. After each completion, move the pointer forward to unlock every venture that is now affordable.

Hint 3

Keep the unlocked ventures' payouts in a max-heap. Pop the largest payout each round, and stop early if the heap is empty or you have done max_ventures rounds.