Minimum toggles to partition a binary array so that it has first 0 s then 1 s | Java program to find minimum toggle required ; Function to calculate minimum toggling required by using Dynamic programming ; Fill entries in zero [ ] such that zero [ i ] stores count of zeroes to the left of i ( exl ; If zero found update zero [ ] array ; Finding the minimum toggle required from every index ( 0 to n - 1 ) ; Driver Program
import java . io . * ; class GFG { static int minToggle ( int arr [ ] , int n ) { int zero [ ] = new int [ n + 1 ] ; zero [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; ++ i ) { if ( arr [ i - 1 ] == 0 ) zero [ i ] = zero [ i - 1 ] + 1 ; else zero [ i ] = zero [ i - 1 ] ; } int ans = n ; for ( int i = 1 ; i <= n ; ++ i ) ans = Math . min ( ans , i - zero [ i ] + zero [ n ] - zero [ i ] ) ; return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 0 , 1 , 1 , 0 } ; int n = arr . length ; System . out . println ( minToggle ( arr , n ) ) ; } }