LeetCode 665: Non-decreasing Array Solution
Master LeetCode problem 665 (Non-decreasing Array), a medium 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.
665. Non-decreasing Array
Problem Explanation
Explanation
To solve this problem, we need to check if the given array can be made non-decreasing by modifying at most one element. We can iterate through the array and whenever we find a decreasing pair of elements, we have two options:
- Modify the current element to make the pair non-decreasing.
- Modify the next element to make the pair non-decreasing.
We need to carefully handle these cases to ensure that we modify at most one element. If there are more than one decreasing pairs, it is impossible to make the array non-decreasing by modifying at most one element.
Algorithm
- Initialize a counter to keep track of the number of modifications needed.
- Iterate through the array from index 1 to n-1.
- If nums[i] < nums[i-1], we have a decreasing pair.
- Increment the counter and check which element to modify to make the pair non-decreasing.
- If i-2 >= 0 and nums[i] < nums[i-2], we need to modify nums[i] to nums[i-1].
- Otherwise, modify nums[i-1] to nums[i].
- After the loop, if the counter is at most 1, return true. Otherwise, return false.
Time Complexity
The time complexity of this algorithm is O(n) where n is the number of elements in the input array.
Space Complexity
The space complexity of this algorithm is O(1) as we are using a constant amount of extra space.
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] < nums[i - 1]) {
count++;
if (i - 2 >= 0 && nums[i] < nums[i - 2]) {
nums[i] = nums[i - 1];
} else {
nums[i - 1] = nums[i];
}
}
}
return count <= 1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 665 (Non-decreasing Array)?
This page provides optimized solutions for LeetCode problem 665 (Non-decreasing 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 665 (Non-decreasing Array)?
The time complexity for LeetCode 665 (Non-decreasing Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 665 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 665 in Java, C++, or Python.