|
| 1 | +/** |
| 2 | + * 1144. Decrease Elements To Make Array Zigzag |
| 3 | + * https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given an array nums of integers, a move consists of choosing any element and decreasing it by 1. |
| 7 | + * |
| 8 | + * An array A is a zigzag array if either: |
| 9 | + * - Every even-indexed element is greater than adjacent elements, ie. |
| 10 | + * A[0] > A[1] < A[2] > A[3] < A[4] > ... |
| 11 | + * - OR, every odd-indexed element is greater than adjacent elements, ie. |
| 12 | + * A[0] < A[1] > A[2] < A[3] > A[4] < ... |
| 13 | + * |
| 14 | + * Return the minimum number of moves to transform the given array nums into a zigzag array. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {number[]} nums |
| 19 | + * @return {number} |
| 20 | + */ |
| 21 | +var movesToMakeZigzag = function(nums) { |
| 22 | + function calculateMoves(peakEven) { |
| 23 | + let moves = 0; |
| 24 | + const adjusted = [...nums]; |
| 25 | + |
| 26 | + for (let i = 0; i < adjusted.length; i++) { |
| 27 | + if ((i % 2 === 0) === peakEven) { |
| 28 | + const left = i > 0 ? adjusted[i - 1] : Infinity; |
| 29 | + const right = i < adjusted.length - 1 ? adjusted[i + 1] : Infinity; |
| 30 | + const target = Math.min(left, right) - 1; |
| 31 | + if (adjusted[i] >= target) { |
| 32 | + moves += adjusted[i] - target; |
| 33 | + adjusted[i] = target; |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + return moves; |
| 39 | + } |
| 40 | + |
| 41 | + const evenPeaks = calculateMoves(true); |
| 42 | + const oddPeaks = calculateMoves(false); |
| 43 | + |
| 44 | + return Math.min(evenPeaks, oddPeaks); |
| 45 | +}; |
0 commit comments