Files

34 lines
1.1 KiB
Python

# 896. Monotonic Array
#
# An array is monotonic if it is either monotone increasing or monotone
# decreasing.
#
# An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j].
# An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].
#
# Given an integer array nums, return true if the given array is monotonic, or
# false otherwise.
# calcular a diferença entre os valores do primeiro e segundo indice.
# guardar 1 se diferença for positiva (nums[1] - nums[0]) > 0
# guardar -1 se diferença for negativa (nums[1] - nums[0]) < 0
# guardar 0 se não houver diferença. actualizar no proximo calculo
def isMonotonic(nums: list[int]) -> bool:
diff: int = 0
for index in range(1, len(nums)):
if diff:
if nums[index] - nums[index - 1] > 0 and diff < 0:
return False
if nums[index] - nums[index - 1] < 0 and diff > 0:
return False
else:
if nums[index] - nums[index - 1] > 0:
diff = 1
elif nums[index] - nums[index - 1] < 0:
diff = -1
else:
diff = 0
return True