896. Monotonic Array
Explanation
To solve this problem, we need to iterate through the given array and check if it is either monotone increasing or monotone decreasing. We can do this by comparing adjacent elements in the array. If all adjacent elements are in non-decreasing order or non-increasing order, the array is monotonic.
- Initialize two variables
isIncreasing
andisDecreasing
astrue
. - Iterate through the array from the second element.
- Update
isIncreasing
tofalse
if any element is greater than the previous element. - Update
isDecreasing
tofalse
if any element is less than the previous element. - If either
isIncreasing
orisDecreasing
isfalse
, the array is not monotonic.
Time complexity: O(n)
Space complexity: O(1)
class Solution {
public boolean isMonotonic(int[] nums) {
boolean isIncreasing = true;
boolean isDecreasing = true;
for (int i = 1; i < nums.length; i++) {
if (nums[i] < nums[i - 1]) {
isIncreasing = false;
}
if (nums[i] > nums[i - 1]) {
isDecreasing = false;
}
}
return isIncreasing || isDecreasing;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.