An array is monotonic if it is either monotone increasing or monotone decreasing.
An array A
is monotone increasing if for all i <= j
, A[i] <= A[j]
. An array A
is monotone decreasing if for all i <= j
, A[i] >= A[j]
.
Return true
if and only if the given array A
is monotonic.
Example:
Input: [1,2,2,3]
Output: true
Approach:
C++
#include <bits/stdc++.h>using namespace std;bool isMonotonic(vector<int> &A){int n = A.size();int i = 1;while (i < n && A[i] >= A[i - 1]){i++;}if (i == n)return true;i = 1;while (i < n && A[i] <= A[i - 1]){i++;}if (i == n)return true;return false;}int main(){vector<int> arr = {1, 2, 2, 3};if (isMonotonic(arr)){cout << "true";}else{cout << "false";}return 0;}
No comments:
Post a Comment