Minimize cost of increments or decrements such that same indexed elements become multiple of each other | Java program for the above approach ; 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
import java . io . * ; class GFG { static int MinimumCost ( int A [ ] , int B [ ] , int N ) { int totalCost = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int mod_A = B [ i ] % A [ i ] ; int totalCost_A = Math . min ( mod_A , A [ i ] - mod_A ) ; int mod_B = A [ i ] % B [ i ] ; int totalCost_B = Math . min ( mod_B , B [ i ] - mod_B ) ; totalCost += Math . min ( totalCost_A , totalCost_B ) ; } return totalCost ; } public static void main ( String [ ] args ) { int A [ ] = { 3 , 6 , 3 } ; int B [ ] = { 4 , 8 , 13 } ; int N = A . length ; System . out . print ( MinimumCost ( A , B , N ) ) ; } }