Maximum elements that can be removed from front of two arrays such that their sum is at most K | 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
function maxItems ( n , m , a , b , K ) { var count = 0 ; var A = new Array ( n + 1 ) ; var B = new Array ( m + 1 ) ; A [ 0 ] = 0 ; B [ 0 ] = 0 ; var i ; for ( i = 1 ; i <= n ; i ++ ) { A [ i ] = a [ i - 1 ] + A [ i - 1 ] ; } for ( i = 1 ; i <= m ; i ++ ) { B [ i ] = b [ i - 1 ] + B [ i - 1 ] ; } for ( i = 0 ; i <= n ; i ++ ) { if ( A [ i ] > K ) break ; var rem = K - A [ i ] ; var j = 0 ; var lo = 0 , hi = m ; while ( lo <= hi ) { var mid = parseInt ( ( lo + hi ) / 2 ) ; if ( B [ mid ] <= rem ) { j = mid ; lo = mid + 1 ; } else { hi = mid - 1 ; } } count = Math . max ( j + i , count ) ; } document . write ( count ) ; } var n = 4 , m = 5 , K = 7 ; var A = [ 2 , 4 , 7 , 3 ] ; var B = [ 1 , 9 , 3 , 4 , 5 ] ; maxItems ( n , m , A , B , K ) ;