Ctrl K

Lower It Into a Sawtooth

Medium
You get an integer array heights. In one move you pick any element and decrease it by 1 (going down to zero or below is allowed). The array is a sawtooth if one of these holds: - every element at an even position is strictly greater than its neighbours: heights[0] > heights[1] < heights[2] > …; - every element at an odd position is strictly greater than its neighbours: heights[0] < heights[1] > heights[2] < …. Return the smallest number of moves that turns the array into a sawtooth.
Example 1
heights=[6, 3, 6, 3, 1] → 3

With peaks at even positions it is enough to lower the 3 at position 3 down to 0, three moves. Peaks at odd positions would cost 8 moves.

Example 2
heights=[2, 7, 4, 6] → 0

The array is already a sawtooth: 2 < 7 > 4 < 6.

Example 3
heights=[5, 5, 5] → 1

Lower the middle element to 4: 5 > 4 < 5. One move.

Constraints
  • 1 ≤ len(heights) ≤ 1000
  • 1 ≤ heights[i] ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTwo Boards Holding Water MediumFewest Jumps to the End MediumReach the Last Cell MediumAs Many Trades as You Like MediumWhere to Start the Lap Medium
loading Python…
Input
heights=[6, 3, 6, 3, 1]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 149 tests on the server, hidden ones included.