LeetCode 2263: Make Array Non-decreasing or Non-increasing Solution
Master LeetCode problem 2263 (Make Array Non-decreasing or Non-increasing), a hard 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.
2263. Make Array Non-decreasing or Non-increasing
Problem Explanation
Explanation
This problem asks us to modify an array in such a way that it becomes non-decreasing or non-increasing by changing at most one element. We can approach this problem by iterating through the array and checking for places where the array is not in either of these orderings. We can then try to adjust the array at those points to make it non-decreasing or non-increasing.
To do this, we can consider two cases:
- If the array is non-decreasing, we need to find the first element that is larger than the next element and adjust it.
- If the array is non-increasing, we need to find the first element that is smaller than the next element and adjust it.
By following this approach and making appropriate adjustments, we can achieve the desired result.
Time Complexity
The time complexity of this approach is O(n) where n is the number of elements in the input array.
Space Complexity
The space complexity of this approach is O(1) as we are not using any extra space apart from a few variables.
Solution Code
class Solution {
public boolean checkPossibility(int[] nums) {
int count = 0;
for (int i = 1; i < nums.length && count <= 1; i++) {
if (nums[i - 1] > nums[i]) {
count++;
if (i - 2 < 0 || nums[i - 2] <= nums[i]) {
nums[i - 1] = nums[i];
} else {
nums[i] = nums[i - 1];
}
}
}
return count <= 1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2263 (Make Array Non-decreasing or Non-increasing)?
This page provides optimized solutions for LeetCode problem 2263 (Make Array Non-decreasing or Non-increasing) 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 2263 (Make Array Non-decreasing or Non-increasing)?
The time complexity for LeetCode 2263 (Make Array Non-decreasing or Non-increasing) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2263 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2263 in Java, C++, or Python.