Maximum elements which can be crossed using given units of a and b | C ++ program to implement the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findElementsCrossed ( int arr [ ] , int a , int b , int n ) { int aa = a ; int ans = 0 ; for ( int 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 ; } int main ( ) { int arr [ ] = { 1 , 0 , 0 , 1 , 0 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int a = 1 ; int b = 2 ; cout << findElementsCrossed ( arr , a , b , n ) ; return 0 ; }