GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • LeetCodeJavascript.com
  • Star on GitHub

This view

  • Original page
  • New address

GeezerVison is showing leetcodejavascript.com — #1243 - Array Transformation - LeetCode JavaScript Solutions

Back to all solutions

#1243 - Array Transformation

Easy • View on LeetCode • View on GitHub
Array Simulation

Problem Description

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.

Solution

/**
 * @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;
};
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.