Monotonic Array Problem


Description

LeetCode Problem 896.

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:

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

Example 2:

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

Example 3:

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

Example 4:

1
2
Input: nums = [1,2,4,5]
Output: true

Example 5:

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

Constraints:

  • 1 <= nums.length <= 10^5
  • -10^5 <= nums[i] <= 10^5


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
    bool isMonotonic(vector<int>& A) {
        bool increase = true;
        bool decrease = true;
        for (int i = 0; i < A.size() - 1; i++) {
            if (A[i] > A[i+1]) 
                increase = false;
            if (A[i] < A[i+1]) 
                decrease = false;
            if (increase == false && decrease == false) 
                return false;
        }
        return true;
    }
};




Related Posts

Walking Robot Simulation Problem

LeetCode 874. A robot on an infinite XY-plane starts at...

Valid Mountain Array Problem

LeetCode 941. Given an array of integers arr, return true...

Sum Of Even Numbers After Queries Problem

LeetCode 985. You are given an integer array nums and...

Partition Array Into Disjoint Intervals Problem

LeetCode 915. Given an integer array nums, partition it into...

Monotonic Array Problem

LeetCode 896. An array is monotonic if it is either...

Maximize Distance To Closest Person Problem

LeetCode 849. You are given an array representing a row...