Monotonic Array
Problem
Return true iff the array is monotonic (entirely non-increasing or entirely non-decreasing).
nums = [1,2,2,3]truedef isMonotonic(nums):
inc = dec = True
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]: dec = False
if nums[i] < nums[i - 1]: inc = False
return inc or dec
function isMonotonic(nums) {
let inc = true, dec = true;
for (let i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1]) dec = false;
if (nums[i] < nums[i - 1]) inc = false;
}
return inc || dec;
}
class Solution {
public boolean isMonotonic(int[] nums) {
boolean inc = true, dec = true;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1]) dec = false;
if (nums[i] < nums[i - 1]) inc = false;
}
return inc || dec;
}
}
bool isMonotonic(vector<int>& nums) {
bool inc = true, dec = true;
for (int i = 1; i < (int)nums.size(); i++) {
if (nums[i] > nums[i - 1]) dec = false;
if (nums[i] < nums[i - 1]) inc = false;
}
return inc || dec;
}
Explanation
An array is monotonic if it only ever goes up (or stays flat) or only ever goes down (or stays flat). The slick trick is to assume both could be true and disprove them as we scan.
We keep two flags, inc and dec, both starting True. Then for each adjacent pair, if a value rises we know it can't be non-increasing, so we set dec = False. If a value drops, it can't be non-decreasing, so inc = False.
Flat pairs (equal values) touch neither flag, which is exactly right since equality is allowed in both directions. At the end, the array is monotonic if at least one flag survives: inc or dec.
Example: [1,2,2,3]. The rises at 1→2 and 2→3 turn dec off, but nothing ever drops, so inc stays True.
Since inc is still true, the result is True. One pass and two booleans settle it.