VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-increasing-array/

⇱ CSES Solutions - Increasing Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Increasing Array

Last Updated : 18 Jul, 2024

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:

  • Initialize a variable ans = 0 to store the minimum number of moves.
  • Start a loop from the second element of the array.
  • For every element, if the previous element is greater than the current element, then add (previous element - current element) to ans and update the current element = previous element.
  • After iterating over all the elements, return ans.

Below is the implementation of the algorithm:


Output
5

Time Complexity: O(N), where N is the size of input array arr[].
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: