Given an array of integers nums, return True if the array is monotonic (either monotone increasing or monotone decreasing), and False otherwise.
An array is monotone increasing if nums[i] <= nums[j] for all i <= j. An array is monotone decreasing if nums[i] >= nums[j] for all i <= j.
Function Signature
def is_monotonic(nums: list[int]) -> bool:
Rules
-
Equal neighboring values are allowed in both directions, so a constant array is monotonic.
-
An array with one element is monotonic.
Constraints
-
1 <= len(nums) <= 10^5
-
-10^5 <= nums[i] <= 10^5
Examples
Input: nums = [1, 2, 2, 3]
Output: True
Each element is greater than or equal to the one before it, so the array is monotone increasing. The repeated 2 does not break that.
Input: nums = [6, 5, 4, 4]
Output: True
Each element is less than or equal to the one before it, so the array is monotone decreasing.
Input: nums = [1, 3, 2]
Output: False
The step from 1 to 3 goes up, so the array is not monotone decreasing, and the step from 3 to 2 goes down, so it is not monotone increasing either.