Leetcode 1827. Minimum Operations to Make the Array Increasing
You are given an integer array nums
(0-indexed). In one operation, you can choose an element of the array and increment it by 1.
nums = [1,2,3]
, you can choose to increment nums[1]
to make nums = [1,3,3]
.Return the minimum number of operations needed to make nums
strictly increasing.
An array nums
is strictly increasing if nums[i] < nums[i+1]
for all 0 <= i < nums.length - 1
. An array of length 1 is trivially strictly increasing.
nums
?nums
?To make the array strictly increasing:
Here is the Java code to solve this problem:
public class Solution {
public int minOperations(int[] nums) {
int operations = 0;
// Traverse the array from the second element
for (int i = 1; i < nums.length; i++) {
// If the current element is not greater than the previous one
if (nums[i] <= nums[i - 1]) {
// Calculate the increments needed to make nums[i] > nums[i - 1]
int incrementNeeded = nums[i - 1] - nums[i] + 1;
// Apply the increments
nums[i] += incrementNeeded;
// Add the increments to the operations counter
operations += incrementNeeded;
}
}
return operations;
}
}
The time complexity of this solution is (O(n)), where (n) is the length of the array nums
. This is because we are performing a single pass through the array to make the necessary adjustments.
The space complexity is (O(1)) since we are not using any additional space that scales with the input size.
nums = [1, 1, 1]
nums[1]
to 2, nums
becomes [1, 2, 1]
(1 operation).nums[2]
to 3, nums
becomes [1, 2, 3]
(2 operations).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?