Maximum elements which can be crossed using given units of a and b | Function to find the number of elements crossed ; Keep a copy of a ; Iterate in the binary array ; If no a and b left to use ; If there is no a ; use b and increase a by 1 if arr [ i ] is 1 ; simply use b ; Use a if theres no b ; Increase a and use b if arr [ i ] == 1 ; Use a ; Driver code
< ? php function findElementsCrossed ( $ arr , $ a , $ b , $ n ) { $ aa = $ a ; $ ans = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ a == 0 && $ b == 0 ) break ; else if ( $ a == 0 ) { if ( $ arr [ $ i ] == 1 ) { $ b -= 1 ; $ a = min ( $ aa , $ a + 1 ) ; } else $ b -= 1 ; } else if ( $ b == 0 ) $ a -- ; else if ( $ arr [ $ i ] == 1 && $ a < $ aa ) { $ b -= 1 ; $ a = min ( $ aa , $ a + 1 ) ; } else $ a -- ; $ ans ++ ; } return $ ans ; } $ arr = array ( 1 , 0 , 0 , 1 , 0 , 1 ) ; $ n = sizeof ( $ arr ) ; $ a = 1 ; $ b = 2 ; echo findElementsCrossed ( $ arr , $ a , $ b , $ n ) ; ? >