Engineering platform~30 min2s · 256 MBtarget O(n) time, O(1) spacedifference-array
A cloud platform plans how many servers to run in each hour of a long planning period. The plan is a profile: one number for every hour.
A capacity tool edits the plan in one way only. It picks a run of neighbouring hours and adds one server to each of them, or removes one server from each of them. The planners want a flat plan, with the same number of servers in every hour. They do not mind which number it is.
What is the fewest number of edits? A plan can have 100,000 hours.
Write fewest_edits(profile).
profile[i] is the number of servers planned for hour i.left..right and either adds 1 to every hour of the range or subtracts 1 from every hour of the range. Hours can go below 0 while you edit.Input: profile = [4, 1, 3, 1, 2]
Output: 5Look at the notes: the difference between each hour and the hour before. One edit changes at most two notes, one up by 1 and one down by 1.
| Between hours | Note | Rise total | Fall total |
|---|---|---|---|
| 0 and 1 | -3 | 0 | 3 |
| 1 and 2 | +2 | 2 | 3 |
| 2 and 3 | -2 | 2 | 5 |
| 3 and 4 | +1 | 3 | 5 |
The rises add up to 3 and the falls to 5. The larger total, 5, is the answer.
Input: profile = [5, 5, 5]
Output: 0The plan is flat already.
Input: profile = [1, 9]
Output: 8Raise hour 0 eight times, or lower hour 1 eight times.
1 ≤ profile.length ≤ 100,000 (hours in the plan)0 ≤ profile[i] ≤ 10,000,000 (servers)The answer can be as large as about 5 × 10^11, so you cannot try edits one by one, and no search over plans can work. The answer must come from a formula in one pass over the notes.
The answer needs a 64-bit integer.