KatInterview

Maximize Resource Harvest with Linear Depletion

Heaps, Sorting & SearchAuto-graded · 25 test cases
MediumAuto-gradedHeaps, Sorting & Searcharraysheaps-sortinggreedy-intervals

Last updated

Find the maximum yield from extracting resources over K time steps when each extraction reduces a site's yield by 1 using binary search on the minimum threshold.

You are managing $N$ resource extraction sites. The array a contains non-negative integers representing the initial yield of each site. If you spend a unit of time at site $i$, you collect its current yield $a[i]$, after which its yield decreases by 1 for future units of time. The yield of any site cannot drop below 0 (harvesting a site with 0 yield yields 0 resources and leaves the yield at 0).

You have a total budget of $k$ units of time. In each time unit, you can choose any single site to harvest. Ponds/sites that are not visited keep their current yields unchanged.

Calculate and return the maximum total resources you can harvest across all $k$ time units.

Constraints

  • $N = \text{len}(a)$, where $1 \le N \le 10^5$
  • $0 \le a[i] \le 10^6$ for each site $i$
  • $0 \le k \le 10^9$

Examples

Example 1

Input: max_fish([90, 100], 100)

Output: 7075

Example 2

Input: max_fish([3, 5], 4)

Output: 15

Example 3

Input: max_fish([2], 5)

Output: 3

Hints

Hint 1

Simulating the process step-by-step with a priority queue takes $O(k \log N)$ time, which is too slow when $k$ is up to $10^9$.

Hint 2

Notice that harvesting a site multiple times yields a strictly decreasing arithmetic sequence of values (e.g., $v, v-1, v-2, \dots, 1$).

Hint 3

Can you use binary search to determine a threshold value $T$ such that we harvest all available yields strictly greater than (or equal to) $T$ across all sites?