-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path1243-array-transformation.js
More file actions
47 lines (42 loc) · 1.24 KB
/
1243-array-transformation.js
File metadata and controls
47 lines (42 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* 1243. Array Transformation
* https://leetcode.com/problems/array-transformation/
* Difficulty: Easy
*
* Given an initial array arr, every day you produce a new array using the array of the
* previous day.
*
* On the i-th day, you do the following operations on the array of day i-1 to produce
* the array of day i:
* - If an element is smaller than both its left neighbor and its right neighbor, then this
* element is incremented.
* - If an element is bigger than both its left neighbor and its right neighbor, then this
* element is decremented.
*
* The first and last elements never change.
*
* After some days, the array does not change. Return that final array.
*/
/**
* @param {number[]} arr
* @return {number[]}
*/
var transformArray = function(arr) {
let current = [...arr];
while (true) {
const next = [...current];
let changed = false;
for (let i = 1; i < current.length - 1; i++) {
if (current[i] < current[i - 1] && current[i] < current[i + 1]) {
next[i]++;
changed = true;
} else if (current[i] > current[i - 1] && current[i] > current[i + 1]) {
next[i]--;
changed = true;
}
}
if (!changed) break;
current = next;
}
return current;
};