📘
LeetCode Practice
  • Index
  • Array
    • 001 Max Consecutive Ones
    • 002 Find Numbers with Even Number of Digits
    • 003 Squares of a Sorted Array
    • 004 Duplicate Zeros
    • 005 Merge Sorted Array
    • 006 Remove Element
    • 007 Remove Duplicates from Sorted Array
    • 008 Check If N and Its Double Exist
    • 09 Valid Mountain Array
    • 10 Replace Elements with Greatest Element on Right Side
Powered by GitBook
On this page
  • Solution
  • Code

Was this helpful?

  1. Array

09 Valid Mountain Array

Previous008 Check If N and Its Double ExistNext10 Replace Elements with Greatest Element on Right Side

Last updated 3 years ago

Was this helpful?

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]

Example 1:

Input: arr = [2,1]
Output: false

Example 2:

Input: arr = [3,5,5]
Output: false

Example 3:

Input: arr = [0,3,2,1]
Output: true

Constraints:

  • 1 <= arr.length <= 104

  • 0 <= arr[i] <= 104

Solution

Code

var validMountainArray = function(arr) {
    let returnNum = true;
    let valleyId = 0;
    for (let index = 0; index < arr.length - 1; index++) {
        if(arr[index] < arr[index+1]){
            console.log(arr[index],arr[index+1],arr.length-1); 
            valleyId = index+1;
        }
        else break;
    }
    console.log("first valley: "+ valleyId)

    if (valleyId == arr.length -1) {
        returnNum = false;
    }

    for (valleyId; valleyId < arr.length-1; valleyId++) {
        if(arr[valleyId] <= arr[valleyId+1] || valleyId == 0) {
            returnNum = false;
        }
    }

    return returnNum;
};