Leetcode 1827. Minimum Operations to Make the Array Increasing
Given an array of integers nums
(0-indexed), you are required to make the array strictly increasing. An array nums
is strictly increasing if nums[i] < nums[i+1]
for every 0 <= i < nums.length - 1
. Return the minimum number of operations needed to make nums
strictly increasing.
In one operation, you can increment an element of the array by 1.
nums
?
10^4
.nums
?
0 <= nums[i] <= 10^4
.nums[i] <= nums[i-1]
).nums[i-1] + 1
. This will ensure the array remains strictly increasing.#include <vector>
class Solution {
public:
int minOperations(std::vector<int>& nums) {
int operations = 0;
for (size_t i = 1; i < nums.size(); ++i) {
if (nums[i] <= nums[i - 1]) {
// The number of increments needed
int increment = nums[i - 1] - nums[i] + 1;
nums[i] += increment;
operations += increment;
}
}
return operations;
}
};
O(n)
, where n
is the length of the array. We only traverse the array once.O(1)
, as we are modifying the array in place and using only a constant amount of extra space.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?