Valid Mountain Array
Problem
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
with0 < i < arr.length - 1
such that:arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Constraints
1 <= arr.length <= 104
0 <= arr[i] <= 104
Solution
The problem Valid Mountain Array
can be solved by checking if the given array consists of strictly increasing and strictly decreasing sequences.
Implementation
static const int fast_io = []()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution
{
public:
bool validMountainArray(vector<int> &arr)
{
int idx = 1;
int size = arr.size();
while (idx < size && arr[idx] > arr[idx - 1])
idx += 1;
if (idx == 1 || idx == size)
return false;
while (idx < size && arr[idx - 1] > arr[idx])
idx += 1;
return idx == size;
}
};