Leetcode 941. Valid Mountain Array
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
i
(0 < i < arr.length - 1) such that:
arr[0] < arr[1] < ... < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
In other words, the array must have at least one peak element and on both sides of the peak, elements should strictly increase up to the peak and strictly decrease beyond the peak.
#include <vector>
bool validMountainArray(std::vector<int>& arr) {
int n = arr.size();
if (n < 3)
return false;
int left = 0;
int right = n - 1;
// Climb the mountain from the left
while (left + 1 < n && arr[left] < arr[left + 1]) {
left++;
}
// Climb the mountain from the right
while (right - 1 >= 0 && arr[right] < arr[right - 1]) {
right--;
}
// Check if the two pointers meet at the same peak point and if it's not at the start or the end
return left > 0 && right < n - 1 && left == right;
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?