fork download
  1. import heapq
  2.  
  3. def solution(N, K, cost, sell):
  4. # Step 1: Create a list of (cost, sell, profit) tuples
  5. items = [(cost[i], sell[i], sell[i] - cost[i]) for i in range(N)]
  6.  
  7. # Step 2: Sort items by cost (cheapest first)
  8. items.sort()
  9.  
  10. # Step 3: Use a max-heap to track the most profitable items we can afford
  11. max_profit = 0
  12. max_heap = [] # Max-heap to store items by highest profit
  13. index = 0
  14.  
  15. while index < N or max_heap:
  16. # Add all items we can afford to the max-heap
  17. while index < N and items[index][0] <= K:
  18. c, s, p = items[index]
  19. heapq.heappush(max_heap, (-p, c, s)) # Store negative profit for max-heap behavior
  20. index += 1
  21.  
  22. # If we can't afford any item, break
  23. if not max_heap:
  24. break
  25.  
  26. # Pick the most profitable item available
  27. profit, c, s = heapq.heappop(max_heap)
  28. max_profit += -profit # Convert back to positive profit
  29. K += -profit # Update cash after selling
  30.  
  31. return max_profit
Success #stdin #stdout 0.07s 14136KB
stdin
Standard input is empty
stdout
Standard output is empty