Monotonic arrays

Written by haloboy777 on 2023-11-16T18:22:34

Figuring out if an array is monotonic

Problem statement

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.

Solution

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.

Code

#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;
}
×