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
aW1wb3J0IGhlYXBxCgpkZWYgc29sdXRpb24oTiwgSywgY29zdCwgc2VsbCk6CiAgICAjIFN0ZXAgMTogQ3JlYXRlIGEgbGlzdCBvZiAoY29zdCwgc2VsbCwgcHJvZml0KSB0dXBsZXMKICAgIGl0ZW1zID0gWyhjb3N0W2ldLCBzZWxsW2ldLCBzZWxsW2ldIC0gY29zdFtpXSkgZm9yIGkgaW4gcmFuZ2UoTildCiAgICAKICAgICMgU3RlcCAyOiBTb3J0IGl0ZW1zIGJ5IGNvc3QgKGNoZWFwZXN0IGZpcnN0KQogICAgaXRlbXMuc29ydCgpCgogICAgIyBTdGVwIDM6IFVzZSBhIG1heC1oZWFwIHRvIHRyYWNrIHRoZSBtb3N0IHByb2ZpdGFibGUgaXRlbXMgd2UgY2FuIGFmZm9yZAogICAgbWF4X3Byb2ZpdCA9IDAKICAgIG1heF9oZWFwID0gW10gICMgTWF4LWhlYXAgdG8gc3RvcmUgaXRlbXMgYnkgaGlnaGVzdCBwcm9maXQKICAgIGluZGV4ID0gMAoKICAgIHdoaWxlIGluZGV4IDwgTiBvciBtYXhfaGVhcDoKICAgICAgICAjIEFkZCBhbGwgaXRlbXMgd2UgY2FuIGFmZm9yZCB0byB0aGUgbWF4LWhlYXAKICAgICAgICB3aGlsZSBpb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