Minimum number of subtract operation to make an array decreasing | CPP program to make an array decreasing ; Function to count minimum no of operation ; Count how many times we have to subtract . ; Check an additional subtraction is required or not . ; Modify the value of arr [ i ] . ; Count total no of operation / subtraction . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_noOf_operation ( int arr [ ] , int n , int k ) { int noOfSubtraction ; int res = 0 ; for ( int i = 1 ; i < n ; i ++ ) { noOfSubtraction = 0 ; if ( arr [ i ] > arr [ i - 1 ] ) { noOfSubtraction = ( arr [ i ] - arr [ i - 1 ] ) / k ; if ( ( arr [ i ] - arr [ i - 1 ] ) % k != 0 ) noOfSubtraction ++ ; arr [ i ] = arr [ i ] - k * noOfSubtraction ; } res = res + noOfSubtraction ; } return res ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 5 ; cout << min_noOf_operation ( arr , N , k ) << endl ; return 0 ; }