Minimize increment | 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
function minimumMoves ( A , B , N ) { var ans = 0 ; var i ; var sum_A = 0 , sum_B = 0 ; for ( i = 0 ; i < N ; i ++ ) { sum_A += A [ i ] ; } for ( i = 0 ; i < N ; i ++ ) { sum_B += B [ i ] ; } if ( sum_A != sum_B ) { return - 1 ; } var i = 0 ; while ( i < N ) { if ( A [ i ] > B [ i ] ) { var temp = A [ i ] - B [ i ] ; var j = i - 1 ; while ( j >= 0 && temp > 0 ) { if ( B [ j ] > A [ j ] ) { var cnt = Math . min ( temp , ( B [ j ] - A [ j ] ) ) ; A [ j ] += cnt ; temp -= cnt ; ans += ( cnt * Math . abs ( j - i ) ) ; } j -- ; } if ( temp > 0 ) { var j = i + 1 ; while ( j < N && temp > 0 ) { if ( B [ j ] > A [ j ] ) { var cnt = Math . min ( temp , ( B [ j ] - A [ j ] ) ) ; A [ j ] += cnt ; temp -= cnt ; ans += ( cnt * Math . abs ( j - i ) ) ; } j ++ ; } } } i ++ ; } return ans ; } var A = [ 1 , 5 , 7 ] ; var B = [ 13 , 0 , 0 ] ; var N = A . length ; document . write ( minimumMoves ( A , B , N ) ) ;