LeetCode 2263: Make Array Non-decreasing or Non-increasing
Problem Description
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.
Solutions
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;
}
}
Loading editor...