896. Monotonic Array
Array, AMateList ·Problem Statement
link: LeetCode.cn LeetCode 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.
Example:
Input: nums = [1,2,2,3]
Output: true
Input: nums = [6,5,4,4]
Output: true
Input: nums = [1,3,2]
Output: false
Constraints: 1 <= nums.length <= 105 -105 <= nums[i] <= 105
Solution Approach
The solution checks whether the array is either entirely non-increasing or non-decreasing by iterating through the elements and verifying both conditions.
Algorithm
- Initialize Flags: Start by assuming the array could be either monotonic increasing or decreasing, and initialize two flags, inc and dec, as True.
- Iterate Through the Array: Loop through the array and compare each element with the next one to check if the array violates the conditions for being monotonic increasing or decreasing, updating the inc and dec flags accordingly.
- Return the Result: After the loop, return True if the array is either entirely non-increasing (dec) or non-decreasing (inc); otherwise, return False.
Implement
class Solution:
def isMonotonic(self, nums: List[int]) -> bool:
inc = True
dec = True
n = len(nums)
for i in range(n - 1):
if nums[i] < nums[i + 1]:
dec = False
elif nums[i] > nums[i + 1]:
inc = False
return dec or inc