KatInterview

Stock Piles Priced by Remaining Count: Maximum Earnings

Greedy & IntervalsAuto-graded · 20 test cases
MediumAuto-gradedGreedy & Intervalsgreedysortingarithmetic-series

Last updated

Greedy selling from the largest pile, solved in bulk with sorting and arithmetic-series sums because the number of sales is too large to simulate one by one.

Selling From Shrinking Piles

A warehouse keeps several separate piles of identical-looking items. The list piles gives the starting size of each pile, so piles[i] is the number of items in pile i.

The price of an item depends on how full its pile is. When you sell one item from a pile, you earn an amount equal to the number of items currently in that pile, counted before the sale. The pile then shrinks by one.

You must make exactly sales sales in total. You may take each sale from any pile that is not empty, in any order. Find the largest total amount you can earn.

Since the total can be huge, return it modulo 1_000_000_007.

Function

Implement max_earnings(piles, sales), which returns the maximum total earnings modulo 1_000_000_007.

  • piles: a list of integers, the starting size of each pile.
  • sales: an integer, the exact number of items to sell.
  • Return value: a single integer, the maximum earnings modulo 1_000_000_007.

The maximum is taken over the exact (non-reduced) totals, and only the final result is reduced modulo 1_000_000_007.

Constraints

  • 1 <= len(piles) <= 10^5
  • 1 <= piles[i] <= 10^9
  • 1 <= sales <= min(sum(piles), 10^9)

Examples

Example 1

Input: max_earnings([2, 5], 4)

Output: 14

Example 2

Input: max_earnings([3, 5], 6)

Output: 19

Hints

Hint 1

Selling from the pile that is currently largest is always at least as good as any other choice. Convince yourself with an exchange argument.

Hint 2

Simulating each sale with a heap is too slow when sales can reach 10^9. Instead, sort the piles in descending order and handle whole 'layers' at once: the k largest piles all drop together from one level to the next distinct level.

Hint 3

Within a layer, the earnings are an arithmetic series repeated for each of the k tied piles. In the last layer, you may not have enough sales to finish it: sell as many complete rows as possible, then the leftover sales all earn the same next value.