Shelf leveling
HardOnline Assessment
Find the cheapest stretch of shelves to bring to one common stock level.
A store has a row of shelves. The string stock has one digit character per shelf, in order, and each digit ("0" to "9") is the number of units on that shelf. A stock clerk will choose k consecutive shelves and bring all k of them to the same stock level. She can choose any whole-number level she likes for the stretch, and the level can be anything, even if no shelf holds that many units right now.
Changing a shelf costs money per unit:
- adding one unit to a shelf costs
add, - removing one unit from a shelf costs
cut.
(Units are bought or discarded, not moved between shelves.) Shelves that are already at the chosen level cost nothing. For a given stretch, the clerk picks the level that makes the total cost smallest.
Input: stock, the string of shelf stocks, the stretch length k, and the unit prices add and cut.
Output: a list [start, cost]: start is the index of the first shelf of the cheapest stretch and cost is its total cost. If several stretches have the same lowest cost, use the one with the smallest start.
The row of shelves can be very long and k can be large, so re-examining each stretch from scratch will be too slow.
Example 1
- Input:
- ["7142",3,1,2]
- Output:
- [1,5]
- Explanation
- Raising costs 1 per unit and cutting costs 2. The stretch starting at 1 holds 1, 4, 2: levelling to 2 costs 1 to raise the first shelf plus 2 x 2 = 4 to cut the second, 5 in total (levelling to 4 also costs 5). The stretch starting at 0 holds 7, 1, 4 and cannot be levelled for less than 9. So the answer is start 1, cost 5.
Example 2
- Input:
- ["59",2,1,3]
- Output:
- [0,4]
- Explanation
- Cutting a unit is three times as expensive as adding one, so it is cheaper to raise the 5 up to the 9 (4 units x 1 = 4) than to cut the 9 down to 5 (4 x 3 = 12). There is only one stretch of 2 shelves, so the answer is start 0, cost 4. Note that the best level is not the middle of the two shelves.
Example 3
- Input:
- ["9090",2,1,1]
- Output:
- [0,9]
- Explanation
- The stretches 9,0 / 0,9 / 9,0 each cost 9 at their best level (add and cut cost the same, so any level from 0 to 9 gives 9). All three tie, and the smallest start wins: [0, 9].
Constraints
1 <= stock.length <= 20,000- every character of
stockis a digit from"0"to"9" 1 <= k <= stock.length1 <= add <= 1,000and1 <= cut <= 1,000