Skip to content

Commit 5918ce1

Browse files
committed
Add solution #1144
1 parent 857ad57 commit 5918ce1

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,150 LeetCode solutions in JavaScript
1+
# 1,151 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -898,6 +898,7 @@
898898
1139|[Largest 1-Bordered Square](./solutions/1139-largest-1-bordered-square.js)|Medium|
899899
1140|[Stone Game II](./solutions/1140-stone-game-ii.js)|Medium|
900900
1143|[Longest Common Subsequence](./solutions/1143-longest-common-subsequence.js)|Medium|
901+
1144|[Decrease Elements To Make Array Zigzag](./solutions/1144-decrease-elements-to-make-array-zigzag.js)|Medium|
901902
1161|[Maximum Level Sum of a Binary Tree](./solutions/1161-maximum-level-sum-of-a-binary-tree.js)|Medium|
902903
1189|[Maximum Number of Balloons](./solutions/1189-maximum-number-of-balloons.js)|Easy|
903904
1200|[Minimum Absolute Difference](./solutions/1200-minimum-absolute-difference.js)|Easy|
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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

Comments
 (0)