LeetCode: Valid Mountain Array Solution

Flagging

Approach

Make sure the array:

• has one peak only
• does not have any valley

Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * @param {number[]} arr3 * @return {boolean}4 */5var validMountainArray = function (arr) {6  let peakCount = 07  let valleyCount = 08  let hasFlatWay = false9
10  for (let i = 1; i < arr.length - 1; i++) {11    if (arr[i] === arr[i - 1] || arr[i] === arr[i + 1]) {12      hasFlatWay = true13    }14    if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) {15      peakCount++16    }17    if (arr[i] < arr[i - 1] && arr[i] < arr[i + 1]) {18      valleyCount++19    }20  }21
22  return peakCount === 1 && valleyCount === 0 && !hasFlatWay23}```

leetcode

array

Next Post

LeetCode: Replace Elements with Greatest Element on Right Side

Jul 25, 2021

Backward iteration, create an array of right max

Previous Post

LeetCode: Check If N and Its Double Exist

Jul 23, 2021

Compare with the iterated elements

Search Posts