Minimize cost to convert all characters of a binary string to 0 s | Java program to implement the above approach ; Function to get the minimum Cost to convert all characters of given string to 0 s ; Stores the range of indexes of characters that need to be flipped ; Stores the number of times current character is flipped ; Stores minimum cost to get the required string ; Traverse the given string ; Remove all value from pq whose value is less than i ; Update flip ; Get the current number ; If current character is flipped odd times ; If current character contains non - zero value ; Update flip ; Update cost ; Append R [ i ] into pq ; Driver Code ; Function call
import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { public static int minCost ( String s , int R [ ] , int C [ ] , int N ) { char ch [ ] = s . toCharArray ( ) ; PriorityQueue < Integer > pq = new PriorityQueue < > ( ) ; int flip = 0 ; int cost = 0 ; for ( int i = 0 ; i < N ; i ++ ) { while ( pq . size ( ) > 0 && pq . peek ( ) < i ) { pq . poll ( ) ; flip -- ; } int cn = ch [ i ] - '0' ; if ( flip % 2 == 1 ) cn = 1 - cn ; if ( cn == 1 ) { flip ++ ; cost += C [ i ] ; pq . add ( R [ i ] ) ; } } return cost ; } public static void main ( String [ ] args ) { int N = 4 ; String s = "1010" ; int R [ ] = { 1 , 2 , 2 , 3 } ; int C [ ] = { 3 , 1 , 2 , 3 } ; System . out . println ( minCost ( s , R , C , N ) ) ; } }