Given an array arr[] containing N integers, the duty is to examine whether or not the array is monotonic or not (monotonic means both the array is in growing order or in reducing order).
Examples:
Enter: arr[] = {1, 2, 2, 3}
Output: Sure
Rationalization: Right here 1 < 2 <= 2 < 3.
The array is in growing order. Due to this fact it’s monotonic.Enter: arr[] = {6, 5, 4, 3}
Output: Sure
Rationalization: Right here 6 > 5 > 4 > 3.
The array is in reducing order. So it’s monotonic.Enter: arr[] = {1, 5, 2}
Output: No
Rationalization: Right here 1 < 5 > 2. The array is neither growing nor reducing.
So the array just isn’t monotonic
Strategy: The issue will be solved by checking if the array is in growing order or in reducing order. This may be simply accomplished within the following manner:
- If for every i in vary [0, N-2], arr[i] ≥ arr[i+1] the array is in reducing order.
- If for every i in vary [0, N-2], arr[i] ≤ arr[i+1], the array is in growing order.
Comply with the under steps to unravel the issue:
- Traverse the array arr[] from i = 0 to N-2 and examine if the array is growing so as
- Traverse the array arr[] from i = 0 to N-2 and examine if the array is reducing so as
- If neither of the above two is true, then the array just isn’t monotonic.
Under is the implementation of the above method:
C++
|
Time Complexity: O(N)
Auxiliary House: O(1)