call(back)
Algorithms & Data StructuresmediumSign in to star problems

Fish From Decaying Ponds

There are n ponds. Pond i currently yields yields[i] fish for one hour of fishing, and every hour you spend at a pond lowers that pond's next yield by one, down to zero. You fish for hours hours in total, choosing any one pond each hour.

Return the largest total number of fish you can catch.

maxFish([90, 100], 100)  ->  7075
maxFish([3, 1], 100)     ->  7      // 3 + 2 + 1 + 1, then every pond is empty

Up to 100,000 ponds, each yield up to 100,000, and hours up to 10,000,000,000. A solution that simulates hour by hour will not finish.

Hints

Hint 1

The greedy is right: always fish the pond with the highest current yield. A max-heap does it in O(hours log n), which is the answer the interviewer rejects.

Hint 2

Picture the yields as bars. The greedy shaves the tallest bars down level by level. After all the hours, every bar taller than some level T has been cut down to T or T + 1.

Hint 3

Binary-search the smallest T for which cutting everything down to T takes at most hours hours. Sum each bar's catch as an arithmetic series, then spend any leftover hours at yield T.

Topics

Asked at

Similar Problems6