[LeetCode] Monotonic Array

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
bool isMonotonic(vector<int>& nums) {
int inc = 0;
for(int i = 0; i < nums.size() - 1; i++) {
if(nums[i] == nums[i+1]) continue;
else if(nums[i] > nums[i+1]) {
if(inc == -1) return false;
inc = 1;
} else {
if(inc == 1) return false;
inc = -1;
}
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/22/PS/LeetCode/monotonic-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.