KatInterview

Boosting Your Budget With a Limited Number of Ventures

Heaps, Sorting & SearchAuto-graded · 20 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapgreedysorting

Last updated

Greedy selection with a sorted unlock pointer and a max-heap: repeatedly pick the most profitable venture whose entry threshold fits the current funds, up to a fixed number of picks.

A small studio starts with a budget of start_funds. It has a list of n possible ventures it could run, and it is allowed to run at most max_ventures of them, one after another, in any order.

Venture i is described by two values:

  • entry[i]: the minimum funds the studio must currently hold in order to begin the venture. This is only a threshold. Nothing is deducted when the venture starts.
  • gain[i]: the amount added to the studio's funds as soon as the venture finishes.

Each venture can be run at most once. Because finished ventures increase the funds, ventures that were out of reach earlier may become available later.

Return the largest total funds the studio can hold after running at most max_ventures ventures.

A venture can be started whenever the current funds are greater than or equal to its entry value. If no remaining venture can be started, the studio stops and its funds stay as they are.

Constraints

  • $1 \le max_ventures \le 10^5$
  • $1 \le n \le 10^5$
  • $0 \le start_funds \le 10^9$
  • $0 \le gain[i] \le 10^4$
  • $0 \le entry[i] \le 10^9$
  • len(gain) == len(entry) == n
  • Your solution should run in about $O((n + k)\log n)$ time, where $k$ is max_ventures. An $O(nk)$ approach is too slow for the largest inputs.

Examples

Example 1

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

Output: 4

Example 2

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

Output: 6

Hints

Hint 1

Funds never go down, because gains are non-negative and entry values are thresholds rather than costs. So a venture that is affordable now stays affordable forever.

Hint 2

At each step, among all ventures you can currently afford, which one leaves you with the most funds? Taking the largest gain never hurts, since more funds only unlock more options.

Hint 3

Sort ventures by entry value and keep a forward-moving pointer to unlock the newly affordable ones. Store unlocked gains in a max-heap (negate values in Python's heapq), and stop early if the heap is empty.