Last Person to Fit in the Bus

medium prefix sum running total sql

Problem

People board a bus one at a time in order of their turn. Each person has a weight, and the bus can carry at most 1000 kilograms. People keep boarding as long as the bus does not exceed the limit; the first person who would push the total over 1000 (and everyone after) stays behind. Return the name of the last person who fits on the bus.

Inputturns = [(Alice,250), (Alex,350), (John,400), (Cynthia,250)]
OutputJohn
Running weights are 250, 600, 1000, 1250. John lands exactly on 1000 — the last who fits. Cynthia would make it 1250, so she is left behind.

SELECT q1.person_name
FROM Queue q1 JOIN Queue q2 ON q1.turn >= q2.turn
GROUP BY q1.turn, q1.person_name, q1.weight
HAVING SUM(q2.weight) <= 1000
ORDER BY SUM(q2.weight) DESC
LIMIT 1;
Time: O(n log n) Space: O(1)