Written on November 16, 2023
Figuring out if an array is monotonic
An array is monotonic if it is either monotone increasing or monotone decreasing. An array is monotone increasing if all its elements from left to right are non-decreasing. An array is monotone decreasing if all its elements from left to right are non-increasing. Given an integer array return true if the given array is monotonic, or false otherwise.
The solution is quite simple. We can iterate over the array and check if it is monotone increasing or monotone decreasing. If it is neither, then it is not monotonic.
#include <iostream>
#include <vector>
bool isMonotonic(std::vector<int> &arr) {
bool increasing = true;
bool decreasing = true;
for (int i = 1; i < arr.size(); i++) {
if (arr[i] < arr[i - 1]) {
increasing = false;
}
if (arr[i] > arr[i - 1]) {
decreasing = false;
}
}
return increasing || decreasing;
}
int main() {
std::vector<int> arr = {1, 2, 3, 4, 5};
std::cout << isMonotonic(arr) << std::endl;
return 0;
}