Minimum increments of Non-Decreasing Subarrays required to make Array Non-Decreasing
Last Updated :
26 Apr, 2021
Given an array arr[] consisting of N integers, the task is to find the minimum number of operations required to make the array non-decreasing, where, each operation involves incrementing all elements of a non-decreasing subarray from the given array by 1.
Examples:
Input: arr[] = {1, 3, 1, 2, 4}
Output: 2
Explanation:
Operation 1: Incrementing arr[2] modifies array to {1, 3, 2, 2, 4}
Operation 2: Incrementing subarray {arr[2], arr[3]} modifies array to {1, 3, 3, 3, 4}
Therefore, the final array is non-decreasing.
Input: arr[] = {1, 3, 5, 10}
Output: 0
Explanation: The array is already non-decreasing.
Approach: Follow the steps below to solve the problem:
- If the array is already a non-decreasing array, then no changes required.
- Otherwise, for any index i where 0 ? i < N, if arr[i] > arr[i+1], add the difference to ans.
- Finally, print ans as answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getMinOps( int arr[], int n)
{
int ans = 0;
for ( int i = 0; i < n - 1; i++)
{
ans += max(arr[i] - arr[i + 1], 0);
}
return ans;
}
int main()
{
int arr[] = { 1, 3, 1, 2, 4 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << (getMinOps(arr, n));
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static int getMinOps( int [] arr)
{
int ans = 0 ;
for ( int i = 0 ; i < arr.length - 1 ; i++) {
ans += Math.max(arr[i] - arr[i + 1 ], 0 );
}
return ans;
}
public static void main(String[] args)
{
int [] arr = { 1 , 3 , 1 , 2 , 4 };
System.out.println(getMinOps(arr));
}
}
|
Python3
def getMinOps(arr):
ans = 0
for i in range ( len (arr) - 1 ):
ans + = max (arr[i] - arr[i + 1 ], 0 )
return ans
arr = [ 1 , 3 , 1 , 2 , 4 ]
print (getMinOps(arr))
|
C#
using System;
class GFG
{
public static int getMinOps( int [] arr)
{
int ans = 0;
for ( int i = 0; i < arr.Length - 1; i++)
{
ans += Math.Max(arr[i] - arr[i + 1], 0);
}
return ans;
}
public static void Main(String[] args)
{
int [] arr = { 1, 3, 1, 2, 4 };
Console.WriteLine(getMinOps(arr));
}
}
|
Javascript
<script>
function getMinOps( arr)
{
let ans = 0;
for (let i = 0; i < arr.length - 1; i++) {
ans += Math.max(arr[i] - arr[i + 1], 0);
}
return ans;
}
let arr = [ 1, 3, 1, 2, 4 ];
document.write(getMinOps(arr));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...