Minimize increment | C # program for 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
using System ; public class GFG { static 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 k = 0 ; while ( k < N ) { if ( A [ k ] > B [ k ] ) { int temp = A [ k ] - B [ k ] ; int j = k - 1 ; while ( j >= 0 && temp > 0 ) { if ( B [ j ] > A [ j ] ) { int cnt = Math . Min ( temp , ( B [ j ] - A [ j ] ) ) ; A [ j ] += cnt ; temp -= cnt ; ans += ( cnt * Math . Abs ( j - k ) ) ; } j -- ; } if ( temp > 0 ) { j = k + 1 ; while ( j < N && temp > 0 ) { if ( B [ j ] > A [ j ] ) { int cnt = Math . Min ( temp , ( B [ j ] - A [ j ] ) ) ; A [ j ] += cnt ; temp -= cnt ; ans += ( cnt * Math . Abs ( j - k ) ) ; } j ++ ; } } } k ++ ; } return ans ; } public static void Main ( string [ ] args ) { int [ ] A = { 1 , 5 , 7 } ; int [ ] B = { 13 , 0 , 0 } ; int N = A . Length ; Console . WriteLine ( minimumMoves ( A , B , N ) ) ; } }