The Wayback Machine - https://web.archive.org/web/20211228023133/https://www.geeksforgeeks.org/minimize-increment-operations-to-make-array-non-decreasing/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Minimize increment operations to make Array non-decreasing

  • Last Updated : 27 Dec, 2021

Given an array arr[] of n integers. Modify the array such that every element is at least as large as the previous element. This can be done by increasing the value of any element by 1. The task is to find the minimum number of moves required to make the array non-decreasing.

Examples:

Input: n = 5, arr[] = {8, 9, 2, 7, 7}
Output: 11
Explanation: The array should be modified to 8 9 9 9 9, this can be done by 11 moves(7 + 2 + 2).

Input: n = 10, arr[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
Output: 0
Explanation: The array is already non decreasing.



Approach: The idea is to traverse the array and at any point when the current element is smaller than the previous one, then make the current one as the previous one and increase the count. Follow the steps below to solve the problem:

  • Initialize the variable count as 0 to store the result.
  • Iterate over the range [0, n) using the variable i and perform the following tasks:
    • If arr[i] is less than arr[i-1] then set the value of arr[i] as arr[i-1] and increase the value of count by arr[i]-arr[i-1].
  • After performing the above steps, print the value of count as the answer.

Below is the implementation of the above approach.

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the minimum
// value of count
long long countMoves(long int arr[], int n)
{
  
    // Variable to store the answer
    long int count = 0;
  
    // Traverse the array
    for (int i = 0; i < n; i++) {
        if (i > 0) {
  
            // Make the changes
            if (arr[i] < arr[i - 1]) {
                count += (arr[i - 1] - arr[i]);
                arr[i] = arr[i - 1];
            }
        }
    }
  
    // Return the answer
    return count;
}
  
// Driver Code
int main()
{
  
    int n = 5;
  
    long int arr[] = { 8, 9, 2, 7, 7 };
  
    cout << countMoves(arr, n);
    return 0;
}
Output
11

Time Complexity: O(N)
Auxiliary Space: O(1)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!