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
def minimumMoves ( A , B , N ) : NEW_LINE INDENT ans = 0 NEW_LINE sum_A = 0 NEW_LINE sum_B = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum_A += A [ i ] NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT sum_B += B [ i ] NEW_LINE DEDENT if ( sum_A != sum_B ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT i = 0 NEW_LINE while ( i < N ) : NEW_LINE INDENT if ( A [ i ] > B [ i ] ) : NEW_LINE INDENT temp = A [ i ] - B [ i ] NEW_LINE j = i - 1 NEW_LINE while ( j >= 0 and temp > 0 ) : NEW_LINE INDENT if ( B [ j ] > A [ j ] ) : NEW_LINE INDENT cnt = min ( temp , ( B [ j ] - A [ j ] ) ) NEW_LINE A [ j ] += cnt NEW_LINE temp -= cnt NEW_LINE ans += ( cnt * abs ( j - i ) ) NEW_LINE DEDENT j -= 1 NEW_LINE DEDENT if ( temp > 0 ) : NEW_LINE INDENT j = i + 1 NEW_LINE while ( j < N and temp > 0 ) : NEW_LINE INDENT if ( B [ j ] > A [ j ] ) : NEW_LINE INDENT cnt = min ( temp , ( B [ j ] - A [ j ] ) ) NEW_LINE A [ j ] += cnt NEW_LINE temp -= cnt NEW_LINE ans += ( cnt * abs ( j - i ) ) NEW_LINE DEDENT j += 1 NEW_LINE DEDENT DEDENT DEDENT i += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 5 , 7 ] NEW_LINE B = [ 13 , 0 , 0 ] NEW_LINE N = len ( A ) NEW_LINE print ( minimumMoves ( A , B , N ) ) NEW_LINE DEDENT