2022-02-28 15:09:19 +00:00
|
|
|
class Solution:
|
|
|
|
def isMonotonic(self, nums: List[int]) -> bool:
|
2022-02-28 15:33:29 +00:00
|
|
|
# Means difference between two nums indicate that it is
|
|
|
|
# decreasing or that difference is 0
|
|
|
|
isNonIncreasing = True
|
2022-02-28 15:09:19 +00:00
|
|
|
|
2022-02-28 15:33:29 +00:00
|
|
|
# Same idea as above butnopposite: it is either increasing
|
|
|
|
# or difference is 0
|
|
|
|
isNonDecreasing = True
|
|
|
|
|
|
|
|
for i in range(1, len(nums)):
|
|
|
|
difference = nums[i] - nums[i - 1]
|
2022-02-28 15:09:19 +00:00
|
|
|
|
2022-02-28 15:33:29 +00:00
|
|
|
# We can say with confidence if this condition ever passes
|
|
|
|
# that sequence is increasing (e.g. 1 2 4 8 ...)
|
|
|
|
if difference > 0:
|
|
|
|
isNonIncreasing = False
|
|
|
|
# Sequence is decreasing (e.g. 1 0 -2 -4 ...)
|
|
|
|
elif difference < 0:
|
|
|
|
isNonDecreasing = False
|
|
|
|
|
|
|
|
# If both flags are set to False, that means there is no
|
|
|
|
# monotonous state and we can break early.
|
|
|
|
if not isNonIncreasing and not isNonDecreasing:
|
2022-02-28 15:09:19 +00:00
|
|
|
return False
|
|
|
|
|
2022-02-28 15:33:29 +00:00
|
|
|
# At the end, if either flag remains True, we have a montonous
|
|
|
|
# array
|
|
|
|
return isNonIncreasing or isNonDecreasing
|