Minimize increment | C ++ Program of the above approach ; Function to calculate the minimum number of operations to convert array A to array B by incrementing and decrementing adjacent elements ; Stores the final count ; Stores the sum of array A and B respectivelly ; Check of the sums are unequall ; Pointer to iterate through array ; Case 1 where A [ i ] > B [ i ] ; Stores the extra values for the current index ; Iterate the array from [ i - 1 , 0 ] ; Stores the count of values being transfered from A [ i ] to A [ j ] ; Add operation count ; Iterate the array in right direction id A [ i ] - B [ i ] > 0 ; Iterate the array from [ i + 1 , n - 1 ] ; Stores the count of values being transfered from A [ i ] to A [ j ] ; Add operation count ; Return Answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumMoves ( int A [ ] , int B [ ] , int N ) { int ans = 0 ; int sum_A = 0 , sum_B = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum_A += A [ i ] ; } for ( int i = 0 ; i < N ; i ++ ) { sum_B += B [ i ] ; } if ( sum_A != sum_B ) { return -1 ; } int i = 0 ; while ( i < N ) { if ( A [ i ] > B [ i ] ) { int temp = A [ i ] - B [ i ] ; int j = i - 1 ; while ( j >= 0 && temp > 0 ) { if ( B [ j ] > A [ j ] ) { int cnt = min ( temp , ( B [ j ] - A [ j ] ) ) ; A [ j ] += cnt ; temp -= cnt ; ans += ( cnt * abs ( j - i ) ) ; } j -- ; } if ( temp > 0 ) { int j = i + 1 ; while ( j < N && temp > 0 ) { if ( B [ j ] > A [ j ] ) { int cnt = min ( temp , ( B [ j ] - A [ j ] ) ) ; A [ j ] += cnt ; temp -= cnt ; ans += ( cnt * abs ( j - i ) ) ; } j ++ ; } } } i ++ ; } return ans ; } int main ( ) { int A [ ] = { 1 , 5 , 7 } ; int B [ ] = { 13 , 0 , 0 } ; int N = sizeof ( A ) / sizeof ( int ) ; cout << minimumMoves ( A , B , N ) ; return 0 ; }