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 — #941 - Valid Mountain Array - LeetCode JavaScript Solutions

Back to all solutions

#941 - Valid Mountain Array

Easy • View on LeetCode • View on GitHub
Array

Problem Description

Given an array of integers arr, return true if and only if it is a valid mountain array.

Recall that arr is a mountain array if and only if:

  • arr.length >= 3
  • There exists some i with 0 < i < arr.length - 1 such that:
    • arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
    • arr[i] > arr[i + 1] > ... > arr[arr.length - 1]

Solution

/**
 * @param {number[]} arr
 * @return {boolean}
 */
var validMountainArray = function(arr) {
  if (arr.length < 3) return false;

  const peakIndex = arr.indexOf(Math.max(...arr));
  if (peakIndex === 0 || peakIndex === arr.length - 1) return false;

  for (let i = 1; i < peakIndex; i++) {
    if (arr[i] <= arr[i - 1]) return false;
  }

  for (let i = peakIndex + 1; i < arr.length; i++) {
    if (arr[i] >= arr[i - 1]) return false;
  }

  return true;
};
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.