LeetCode 2289: Steps to Make Array Non-decreasing Solution
Master LeetCode problem 2289 (Steps to Make Array Non-decreasing), 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.
2289. Steps to Make Array Non-decreasing
Problem Explanation
Explanation:
To solve this problem, we need to iterate through the array and adjust elements to make the array non-decreasing. We can achieve this by modifying any element nums[i] such that nums[i - 1] <= nums[i]. If nums[i - 1] > nums[i], we need to adjust either nums[i - 1] or nums[i] to make the array non-decreasing.
We can count the number of steps needed to make the array non-decreasing by iterating through the array and adjusting elements whenever necessary. By doing this, we can keep track of the number of steps required.
Algorithm:
- Initialize a variable
countto 0 to keep track of the number of steps. - Iterate through the array starting from index 1.
- If nums[i - 1] > nums[i]:
- Increment
count. - If nums[i - 2] > nums[i], update nums[i] to nums[i - 1].
- Otherwise, update nums[i - 1] to nums[i].
- Increment
- After iterating through the array, return the final
count.
Time Complexity: The time complexity of this algorithm is O(n) where n is the length of the input array nums.
Space Complexity: The space complexity of this algorithm is O(1) as we are not using any extra space other than a few variables.
:
Solution Code
class Solution {
public int makeArrayNonDecreasing(int[] nums) {
int count = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i - 1] > nums[i]) {
count++;
if (i - 2 >= 0 && nums[i - 2] > nums[i]) {
nums[i] = nums[i - 1];
} else {
nums[i - 1] = nums[i];
}
}
}
return count;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2289 (Steps to Make Array Non-decreasing)?
This page provides optimized solutions for LeetCode problem 2289 (Steps to Make Array Non-decreasing) 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 2289 (Steps to Make Array Non-decreasing)?
The time complexity for LeetCode 2289 (Steps to Make Array Non-decreasing) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2289 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2289 in Java, C++, or Python.