LeetCode 896: Monotonic Array Solution
Master LeetCode problem 896 (Monotonic Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
896. Monotonic Array
Problem Explanation
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
isIncreasingandisDecreasingastrue. - Iterate through the array from the second element.
- Update
isIncreasingtofalseif any element is greater than the previous element. - Update
isDecreasingtofalseif any element is less than the previous element. - If either
isIncreasingorisDecreasingisfalse, the array is not monotonic.
Time complexity: O(n)
Space complexity: O(1)
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 896 (Monotonic Array)?
This page provides optimized solutions for LeetCode problem 896 (Monotonic Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 896 (Monotonic Array)?
The time complexity for LeetCode 896 (Monotonic Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 896 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 896 in Java, C++, or Python.