Skip to content

Instantly share code, notes, and snippets.

@misterpoloy
Created May 12, 2020 04:58
Show Gist options
  • Save misterpoloy/ae293217f6e2b6451008f192d4180ba7 to your computer and use it in GitHub Desktop.
Save misterpoloy/ae293217f6e2b6451008f192d4180ba7 to your computer and use it in GitHub Desktop.
An array is said to be monotonic if its elements, from left to right, are entirely no-increasing or enteriley non-decreasing.
using namespace std;
// O(n) time | O(i) space -where n is the length of the arrat
bool isMonotonic(vector<int> array) {
if (array.size() < 2) return true;
int is_non_increasing = true;
int is_non_decreasing = true;
for (int i = 1; i < array.size(); i++) {
if (array[i] > array[i - 1]) { // increasing
is_non_increasing = false;
}
if (array[i] < array[i - 1]) { // decreasing
is_non_decreasing = false;
}
}
return is_non_decreasing || is_non_increasing;
}
@misterpoloy
Copy link
Author

Monotonic Arrat

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment