[LeetCode] Array Transformation

1243. Array Transformation

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:

  1. If an element is smaller than both its left neighbor and its right neighbor, then this element is incremented.
  2. If an element is bigger than both its left neighbor and its right neighbor, then this element is decremented.
  3. The first and last elements never change.

After some days, the array does not change. Return that final array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
vector<int> transformArray(vector<int>& arr) {
while(1) {
vector<int> now = arr;
for(int i = 1; i < arr.size() - 1; i++) {
if(arr[i-1] > arr[i] and arr[i] < arr[i+1]) now[i]++;
else if(arr[i-1] < arr[i] and arr[i] > arr[i+1]) now[i]--;
}

if(now == arr) break;
swap(arr,now);
}
return arr;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/05/14/PS/LeetCode/array-transformation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.