Minimize cost of increments or decrements such that same indexed elements become multiple of each other | Function to find the minimum cost to make A [ i ] multiple of B [ i ] or vice - versa for every array element ; Stores the minimum cost ; Traverse the array ; Case 1 : Update A [ i ] ; Case 2 : Update B [ i ] ; Add the minimum of the above two cases ; Return the resultant cost ; Driver Code
function MinimumCost ( A , B , N ) { var totalCost = 0 ; for ( i = 0 ; i < N ; i ++ ) { var mod_A = B [ i ] % A [ i ] ; var totalCost_A = Math . min ( mod_A , A [ i ] - mod_A ) ; var mod_B = A [ i ] % B [ i ] ; var totalCost_B = Math . min ( mod_B , B [ i ] - mod_B ) ; totalCost += Math . min ( totalCost_A , totalCost_B ) ; } return totalCost ; } var A = [ 3 , 6 , 3 ] ; var B = [ 4 , 8 , 13 ] ; var N = A . length ; document . write ( MinimumCost ( A , B , N ) ) ;