![]() |
VOOZH | about |
Given an array arr[] of size N, you want to modify the array so that it is increasing, i.e., every element is at least as large as the previous element. On each move, you may increase the value of any element by one. Find the minimum number of moves required.
Examples:
Input: N = 5, arr[] = {3, 2, 5, 1, 7}
Output: 5
Explanation:
- Increase arr[1] by 1, so arr[] becomes {3, 3, 5, 1, 7}.
- Increase arr[3] by 4, so arr[] becomes {3, 3, 5, 5, 7}.
Input: N = 3, arr[] = {1, 2, 3}
Output: 0
Explanation: No moves are needed as the array is already in increasing order.
Algorithm: To solve the problem, follow the below idea:
The problem can be solved by traversing the array and comparing each element with its previous element. If the current element is smaller than the previous element so we need to increase the current element till it becomes equal to the previous element. This can be done by applying increment operations (previous element - current element) number of times. Sum of all these operations will be the minimum number of moves required.
Step-by-step algorithm:
Below is the implementation of the algorithm:
5
Time Complexity: O(N), where N is the size of input array arr[].
Auxiliary Space: O(1)