Problem Description –
There is a queue of people waiting to board a bus. However, the bus has a weight limit of
1000 kilograms, so there may be some people who cannot board.
Write an SQL query to find the
person_name of the last person that can fit on the bus without exceeding the weight limit. The test cases are generated such that the first person does not exceed the weight limit.
The query result format is in the following example.
Difficulty Level – Medium
Problem Link – Last Person in Bus
SELECT person_name FROM ( SELECT person_name, weight, SUM(weight) OVER(ORDER BY turn, person_id) as total_weight FROM Queue ) x WHERE total_weight <= 1000 ORDER BY total_weight DESC LIMIT 1
This is basically a Running Total problem. First in the inner query we calculate the running total then in the outer query we filter the results to less than or equal to 1000 kg, order the data by total weight in descending order and limit the result to 1 to get the right result.