Maximum elements that can be removed from front of two arrays such that their sum is at most K | Java program for the above approach ; Function to find the maximum number of items that can be removed from both the arrays ; Stores the maximum item count ; Stores the prefix sum of the cost of items ; Insert the item cost 0 at the front of the arrays ; Build the prefix sum for the array A [ ] ; Update the value of A [ i ] ; Build the prefix sum for the array B [ ] ; Update the value of B [ i ] ; Iterate through each item of the array A [ ] ; If A [ i ] exceeds K ; Store the remaining amount after taking top i elements from the array A ; Store the number of items possible to take from the array B [ ] ; Store low and high bounds for binary search ; Binary search to find number of item that can be taken from stack B in rem amount ; Calculate the mid value ; Update the value of j and lo ; Update the value of the hi ; Store the maximum of total item count ; Print the result ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static void maxItems ( int n , int m , int a [ ] , int b [ ] , int K ) { int count = 0 ; int A [ ] = new int [ n + 1 ] ; int B [ ] = new int [ m + 1 ] ; A [ 0 ] = 0 ; B [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { A [ i ] = a [ i - 1 ] + A [ i - 1 ] ; } for ( int i = 1 ; i <= m ; i ++ ) { B [ i ] = b [ i - 1 ] + B [ i - 1 ] ; } for ( int i = 0 ; i <= n ; i ++ ) { if ( A [ i ] > K ) break ; int rem = K - A [ i ] ; int j = 0 ; int lo = 0 , hi = m ; while ( lo <= hi ) { int mid = ( lo + hi ) / 2 ; if ( B [ mid ] <= rem ) { j = mid ; lo = mid + 1 ; } else { hi = mid - 1 ; } } count = Math . max ( j + i , count ) ; } System . out . print ( count ) ; } public static void main ( String [ ] args ) { int n = 4 , m = 5 , K = 7 ; int A [ ] = { 2 , 4 , 7 , 3 } ; int B [ ] = { 1 , 9 , 3 , 4 , 5 } ; maxItems ( n , m , A , B , K ) ; } }