Minimize cost to modify the Array such that even indices have even elements and vice versa | Java program for the above approach ; Function to find the minimum cost to modify the array according to the given criteria ; Count of wrong positioned odd and even elements ; Odd Count ; Even Count ; Swapping Cost ; Decrementing cost after swapping ; Only decrementing cost ; Return the minimum cost of the two cases ; Driver Code
class GFG { public static int minimumCost ( int arr [ ] , int N , int X , int Y ) { int even_count = 0 , odd_count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( ( arr [ i ] & 1 ) > 0 && ( i % 2 == 0 ) ) { odd_count ++ ; } if ( ( arr [ i ] % 2 ) == 0 && ( i & 1 ) > 0 ) { even_count ++ ; } } int cost1 = X * Math . min ( odd_count , even_count ) ; int cost2 = Y * ( Math . max ( odd_count , even_count ) - Math . min ( odd_count , even_count ) ) ; int cost3 = ( odd_count + even_count ) * Y ; return Math . min ( cost1 + cost2 , cost3 ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 5 , 3 , 7 , 2 , 1 } , X = 10 , Y = 2 ; int N = arr . length ; System . out . println ( minimumCost ( arr , N , X , Y ) ) ; } }