Code Logo

Minimum Operations to Make Array Increasing

Published at24 Jul 2026
Easy 0 views
Like0

Given an integer array nums, you need to make it strictly increasing by incrementing elements. In one operation you can increment any element by 1. Find the minimum number of operations needed.

The greedy DP approach processes the array left to right. For each index i starting from 1, if nums[i] is not greater than nums[i-1], it must be raised. The minimum valid value for nums[i] is nums[i-1] + 1. The number of operations for this position is the difference between this minimum and the current value. After incrementing, update nums[i] to its new value so later comparisons are correct.

This greedy is optimal because raising an element more than necessary would waste operations. Each element is processed exactly once, and the decision at each step depends only on the previous element's final value. Time is O(n), space is O(1) (the input array is modified in place).

Edge cases include empty or single-element arrays (return 0), arrays that are already strictly increasing (return 0), and arrays where each element must be raised significantly.

The operations problem illustrates how a greedy DP can use the previous element's value as state to determine the minimum required value for the current element. This pattern appears in many array manipulation optimization problems.

Example Input & Output

Example 1
Input
[]
Output
0
Explanation

Empty.

Example 2
Input
[1]
Output
0
Explanation

Single.

Example 3
Input
[1,2,3]
Output
0
Explanation

Already increasing.

Example 4
Input
[1,5,2,4,3]
Output
12
Explanation

[1,5,6,7,8]: 4+3+5=12.

Example 5
Input
[1,1,1]
Output
3
Explanation

[1,2,3]: ops=0+1+2=3.

Algorithm Flow

Recommendation Algorithm Flow for Minimum Operations to Make Array Increasing
Recommendation Algorithm Flow for Minimum Operations to Make Array Increasing

Solution Approach

For each i, if nums[i] <= nums[i-1], add difference to ops and update nums[i].

function solution(nums) {
  var ops = 0;
  for (var i = 1; i < nums.length; i++) {
    if (nums[i] <= nums[i-1]) {
      var diff = nums[i-1] + 1 - nums[i];
      ops += diff;
      nums[i] += diff;
    }
  }
  return ops;
}

Time O(n), Space O(1).

Best Answers

java
class Solution {
    public int solution(int[] nums) {
        int ops=0;
        for (int i=1;i<nums.length;i++) {
            if (nums[i]<=nums[i-1]) {
                int d=nums[i-1]+1-nums[i];
                ops+=d;
                nums[i]+=d;
            }
        }
        return ops;
    }
}