Minimize increment operations to make Array non-decreasing
Last Updated :
10 Jan, 2022
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++
#include <bits/stdc++.h>
using namespace std;
long long countMoves( long int arr[], int n)
{
long int count = 0;
for ( int i = 0; i < n; i++) {
if (i > 0) {
if (arr[i] < arr[i - 1]) {
count += (arr[i - 1] - arr[i]);
arr[i] = arr[i - 1];
}
}
}
return count;
}
int main()
{
int n = 5;
long int arr[] = { 8, 9, 2, 7, 7 };
cout << countMoves(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG{
static long countMoves( int arr[], int n)
{
int count = 0 ;
for ( int i = 0 ; i < n; i++) {
if (i > 0 ) {
if (arr[i] < arr[i - 1 ]) {
count += (arr[i - 1 ] - arr[i]);
arr[i] = arr[i - 1 ];
}
}
}
return count;
}
public static void main(String[] args)
{
int n = 5 ;
int arr[] = { 8 , 9 , 2 , 7 , 7 };
System.out.print(countMoves(arr, n));
}
}
|
Python3
def countMoves(arr, n):
count = 0
for i in range (n):
if (i > 0 ):
if (arr[i] < arr[i - 1 ]):
count + = (arr[i - 1 ] - arr[i])
arr[i] = arr[i - 1 ]
return count
n = 5
arr = [ 8 , 9 , 2 , 7 , 7 ]
print (countMoves(arr, n))
|
C#
using System;
class GFG
{
static long countMoves( int []arr, int n)
{
int count = 0;
for ( int i = 0; i < n; i++) {
if (i > 0) {
if (arr[i] < arr[i - 1]) {
count += (arr[i - 1] - arr[i]);
arr[i] = arr[i - 1];
}
}
}
return count;
}
public static void Main()
{
int n = 5;
int []arr = { 8, 9, 2, 7, 7 };
Console.Write(countMoves(arr, n));
}
}
|
Javascript
<script>
function countMoves(arr, n) {
let count = 0;
for (let i = 0; i < n; i++) {
if (i > 0) {
if (arr[i] < arr[i - 1]) {
count += (arr[i - 1] - arr[i]);
arr[i] = arr[i - 1];
}
}
}
return count;
}
let n = 5;
let arr = [8, 9, 2, 7, 7];
document.write(countMoves(arr, n));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...