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 ; 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
def maxItems ( n , m , a , b , K ) : NEW_LINE INDENT count = 0 NEW_LINE A = [ 0 for i in range ( n + 1 ) ] NEW_LINE B = [ 0 for i in range ( m + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT A [ i ] = a [ i - 1 ] + A [ i - 1 ] NEW_LINE DEDENT for i in range ( 1 , m + 1 , 1 ) : NEW_LINE INDENT B [ i ] = b [ i - 1 ] + B [ i - 1 ] NEW_LINE DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT if ( A [ i ] > K ) : NEW_LINE INDENT break NEW_LINE DEDENT rem = K - A [ i ] NEW_LINE j = 0 NEW_LINE lo = 0 NEW_LINE hi = m NEW_LINE while ( lo <= hi ) : NEW_LINE INDENT mid = ( lo + hi ) // 2 NEW_LINE if ( B [ mid ] <= rem ) : NEW_LINE INDENT j = mid NEW_LINE lo = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT hi = mid - 1 NEW_LINE DEDENT DEDENT count = max ( j + i , count ) NEW_LINE DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE m = 5 NEW_LINE K = 7 NEW_LINE A = [ 2 , 4 , 7 , 3 ] NEW_LINE B = [ 1 , 9 , 3 , 4 , 5 ] NEW_LINE maxItems ( n , m , A , B , K ) NEW_LINE DEDENT