941. Valid Mountain Array
Python
Single Loop Solution
335 ms, 15.4MB
class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
length = len(arr)
if length < 3:
return False
top_index = 0
is_reach_top = False
for i in range(1, length):
# Increasing
if arr[i] > arr[i-1] and not is_reach_top:
top_index = i
continue
# Decreasing
if arr[i] < arr[i-1]:
is_reach_top = True
continue
return False
return top_index != 0 and top_index != length - 1
Break Loop Solution
192 ms, 15.6MB
class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
length = len(arr)
if length < 3:
return False
i = 0
while i < length-1:
if arr[i] < arr[i+1]:
i += 1
else:
break
if i == 0 or i == length-1:
return False
while i < length-1:
if arr[i] > arr[i+1]:
i += 1
else:
break
return i == length-1