Stock Piles Priced by Remaining Count: Maximum Earnings
Greedy & IntervalsAuto-graded · 20 test casesLast 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^51 <= piles[i] <= 10^91 <= 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every sale earns the current size of the chosen pile, and sizes only go down. So the best strategy is to always sell from the currently largest pile. Equivalently, pile i offers the values piles[i], piles[i]-1, ..., 1, and we want the sales largest values from all of these combined.
Selling one item at a time is too slow, because sales can be 10^9. Instead, sort the piles in descending order, append a 0 as a floor, and process the values in layers:
- At index
i, thetied = i + 1largest piles have all been brought down to heighttop = levels[i]. The next distinct level isbottom = levels[i+1]. - Bringing all of them from
topdown tobottomsellstied * (top - bottom)items. Each pile contributestop, top-1, ..., bottom+1. - If we have at least that many sales left, take the whole layer. Its earnings are
tied * (top + bottom + 1) * height / 2(an arithmetic series), and we subtract its capacity fromsales. - Otherwise this is the final layer. Do
full_rows = sales // tiedcomplete rows, which earntied * (top + lowest) * full_rows / 2withlowest = top - full_rows + 1. Theextra = sales % tiedremaining sales all earntop - full_rows, and it does not matter which tied piles supply them.
Why it is correct
- Greedy choice: if a plan sells at value
vwhile some pile offersu > v, moving that sale to the larger pile does not decrease earnings. So some optimal plan always sells at the current maximum. - Layers: the layers enumerate the union of all piles' value sequences in descending order, so taking the first
salesof them gives the topsalesvalues. - Final layer: all tied piles have the same value at each row, so full rows come first and the leftover (fewer than
tied) sales all earn the same value. - Termination: since
sales <= sum(piles), the layers always supply enough items.
Python integers do not overflow, so the modulus is applied once at the end. The products are always even where halved, so the integer division is exact.
Complexity
- Time:
O(n log n)for sorting plusO(n)for the sweep. - Space:
O(n)for the sorted copy.
Reference solution
from typing import List
MOD = 1_000_000_007
def max_earnings(piles: List[int], sales: int) -> int:
levels = sorted(piles, reverse=True)
levels.append(0) # floor beneath the smallest pile
total = 0
n = len(piles)
for i in range(n):
top = levels[i]
bottom = levels[i + 1]
tied = i + 1 # piles currently at height `top`
height = top - bottom
capacity = tied * height # sales available in this layer
if sales >= capacity:
# Sell values top, top-1, ..., bottom+1 from each tied pile.
total += tied * (top + bottom + 1) * height // 2
sales -= capacity
else:
full_rows, extra = divmod(sales, tied)
if full_rows:
lowest = top - full_rows + 1
total += tied * (top + lowest) * full_rows // 2
# Remaining sales all happen at the next value down.
total += extra * (top - full_rows)
return total % MOD
return total % MOD