A monotonic array is an array that is either entirely non-increasing or non-decreasing.
Given an array nums
, return true
if the given array is monotonic, or false
otherwise.
nums = [1,2,2,3]
Output: true
nums = [6,5,4,4]
Output: true
nums = [1,3,2]
Output: false
nums = [1,2,4,5]
Output: true
nums = [1,1,1]
Output: true
1 <= nums.length <= 10^5
-10^5 <= nums[i] <= 10^5
1 <= nums.length
.true
because a single element array is considered monotonic.true
.true
.public class Solution {
public boolean isMonotonic(int[] nums) {
if (nums.length == 1) {
return true;
}
boolean isNonDecreasing = true;
boolean isNonIncreasing = true;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1]) {
isNonIncreasing = false;
}
if (nums[i] < nums[i - 1]) {
isNonDecreasing = false;
}
}
return isNonDecreasing || isNonIncreasing;
}
public static void main(String[] args) {
Solution sol = new Solution();
// Examples
System.out.println(sol.isMonotonic(new int[]{1, 2, 2, 3})); // true
System.out.println(sol.isMonotonic(new int[]{6, 5, 4, 4})); // true
System.out.println(sol.isMonotonic(new int[]{1, 3, 2})); // false
System.out.println(sol.isMonotonic(new int[]{1, 2, 4, 5})); // true
System.out.println(sol.isMonotonic(new int[]{1, 1, 1})); // true
}
}
n
is the length of the array.This solution efficiently determines whether the array is monotonic by checking both possible monotonic patterns in a single pass.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?