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.
 

Example 1:

Input: nums = [1,2,2,3]
Output: true

Example 2:

Input: nums = [6,5,4,4]
Output: true

Example 3:

Input: nums = [1,3,2]
Output: false

Constraints:
  • 1 < = n u m s . l e n g t h < = 1 0 5 1 <= nums.length <= 10^5 1<=nums.length<=105
  • − 1 0 5 < = n u m s [ i ] < = 1 0 5 -10^5 <= nums[i] <= 10^5 105<=nums[i]<=105

From: LeetCode
Link: 896. Monotonic Array


Solution:

Ideas:
  • Track both possibilities: non-decreasing and non-increasing.

  • Knock out a possibility when a violating pair appears.

  • Early exit if both become false.

  • Handles duplicates naturally (e.g., [2,2,2] is monotonic).

Code:
bool isMonotonic(int* nums, int numsSize) {
    if (numsSize <= 2) return true;

    bool nonDecreasing = true;
    bool nonIncreasing = true;

    for (int i = 1; i < numsSize; ++i) {
        if (nums[i] > nums[i - 1]) nonIncreasing = false;
        if (nums[i] < nums[i - 1]) nonDecreasing = false;
        if (!nonDecreasing && !nonIncreasing) return false; // early exit
    }
    return true;
}
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐