Array Transformation

easy array simulation

Problem

Given an initial array arr, transform it daily by the following rules. For every interior element (not the first or last): if it is strictly smaller than both neighbors, increment it by 1; if it is strictly larger than both neighbors, decrement it by 1. All comparisons in a single day use the values from the start of that day. Keep transforming until no value changes, then return the final array.

Inputarr = [6, 2, 3, 4]
Output[6, 3, 3, 4]
On day 1, index 1 (value 2) is a local min between 6 and 3, so it becomes 3. No other interior element changes, and day 2 produces no change, so the array is stable.

def transform_array(arr):
    changed = True
    while changed:
        changed = False
        prev = arr[:]
        for i in range(1, len(arr) - 1):
            if prev[i] < prev[i - 1] and prev[i] < prev[i + 1]:
                arr[i] += 1
                changed = True
            elif prev[i] > prev[i - 1] and prev[i] > prev[i + 1]:
                arr[i] -= 1
                changed = True
    return arr
function transformArray(arr) {
  let changed = true;
  while (changed) {
    changed = false;
    const prev = arr.slice();
    for (let i = 1; i < arr.length - 1; i++) {
      if (prev[i] < prev[i - 1] && prev[i] < prev[i + 1]) {
        arr[i]++;
        changed = true;
      } else if (prev[i] > prev[i - 1] && prev[i] > prev[i + 1]) {
        arr[i]--;
        changed = true;
      }
    }
  }
  return arr;
}
class Solution {
    public int[] transformArray(int[] arr) {
        boolean changed = true;
        while (changed) {
            changed = false;
            int[] prev = arr.clone();
            for (int i = 1; i < arr.length - 1; i++) {
                if (prev[i] < prev[i - 1] && prev[i] < prev[i + 1]) {
                    arr[i]++;
                    changed = true;
                } else if (prev[i] > prev[i - 1] && prev[i] > prev[i + 1]) {
                    arr[i]--;
                    changed = true;
                }
            }
        }
        return arr;
    }
}
vector<int> transformArray(vector<int>& arr) {
    bool changed = true;
    while (changed) {
        changed = false;
        vector<int> prev = arr;
        for (int i = 1; i < (int)arr.size() - 1; i++) {
            if (prev[i] < prev[i - 1] && prev[i] < prev[i + 1]) {
                arr[i]++;
                changed = true;
            } else if (prev[i] > prev[i - 1] && prev[i] > prev[i + 1]) {
                arr[i]--;
                changed = true;
            }
        }
    }
    return arr;
}
Time: O(n · m) Space: O(n)