Skip to content

941. Valid Mountain Array 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  bool validMountainArray(vector<int>& A) {
    if (A.size() < 3)
      return false;

    int l = 0;
    int r = A.size() - 1;

    while (l + 1 < A.size() && A[l] < A[l + 1])
      ++l;
    while (r > 0 && A[r] < A[r - 1])
      --r;

    return l > 0 && r < A.size() - 1 && l == r;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public boolean validMountainArray(int[] A) {
    if (A.length < 3)
      return false;

    int l = 0;
    int r = A.length - 1;

    while (l + 1 < A.length && A[l] < A[l + 1])
      ++l;
    while (r > 0 && A[r] < A[r - 1])
      --r;

    return l > 0 && r < A.length - 1 && l == r;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def validMountainArray(self, A: List[int]) -> bool:
    if len(A) < 3:
      return False

    l = 0
    r = len(A) - 1

    while l + 1 < len(A) and A[l] < A[l + 1]:
      l += 1
    while r > 0 and A[r] < A[r - 1]:
      r -= 1

    return l > 0 and r < len(A) - 1 and l == r
Back to top