import heapq

def solution(N, K, cost, sell):
    # Step 1: Create a list of (cost, sell, profit) tuples
    items = [(cost[i], sell[i], sell[i] - cost[i]) for i in range(N)]
    
    # Step 2: Sort items by cost (cheapest first)
    items.sort()

    # Step 3: Use a max-heap to track the most profitable items we can afford
    max_profit = 0
    max_heap = []  # Max-heap to store items by highest profit
    index = 0

    while index < N or max_heap:
        # Add all items we can afford to the max-heap
        while index < N and items[index][0] <= K:
            c, s, p = items[index]
            heapq.heappush(max_heap, (-p, c, s))  # Store negative profit for max-heap behavior
            index += 1

        # If we can't afford any item, break
        if not max_heap:
            break

        # Pick the most profitable item available
        profit, c, s = heapq.heappop(max_heap)
        max_profit += -profit  # Convert back to positive profit
        K += -profit  # Update cash after selling

    return max_profit