#1827
Minimum Operations to Make the Array Increasing
EasyArrayGreedyGreedyArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses a greedy strategy to ensure each element is at least one greater than the previous element. This avoids unnecessary increments and ensures we only make the minimum number of operations needed.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a variable 'operations' to 0 and set 'prev' to the first element.
- 2Step 2: Loop through the array starting from the second element.
- 3Step 3: If the current element is less than or equal to 'prev', calculate the increments needed to make it 'prev + 1', update 'operations', and set 'prev' to this new value. Otherwise, just update 'prev' to the current element.
solution.py10 lines
1def minOperations(nums):
2 operations = 0
3 prev = nums[0]
4 for i in range(1, len(nums)):
5 if nums[i] <= prev:
6 operations += (prev - nums[i] + 1)
7 prev += 1
8 else:
9 prev = nums[i]
10 return operationsℹ
Complexity note: This complexity is optimal because we only make a single pass through the array, checking each element once.
- 1Each element must be strictly greater than the previous one.
- 2Incrementing an element affects only the current and subsequent elements.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.