29- Monotonic Array
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
Initialize two boolean flags, increasing
and decreasing
, to true
. These flags will help us track whether the array is non-increasing or non-decreasing, respectively.
Iterate through the array nums
starting from index 1
(comparing each element with the previous one).
For each pair of adjacent elements, check whether nums[i]
is greater than nums[i - 1]
. If it is, set the decreasing flag to false because this indicates that the array is not decreasing.
If nums[i]
is less than nums[i - 1]
, set the increasing
flag to false because this indicates that the array is not increasing.
Continue this process for the entire array.
After the loop, check whether either increasing
or decreasing
is true
. If either of them is true, it means that the array is monotonic (either non-increasing or non-decreasing), so return true
. Otherwise, return false
.
Time Complexity: O(n)
Auxiliary Space Complexity: O(1)
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.