Last Person to Fit in the Bus LeetCode Solution

Last updated on October 9th, 2024 at 10:15 pm

This Leetcode problem Last Person to Fit in the Bus LeetCode Solution is done in SQL.

List of all LeetCode Solution

Level of Question

Medium

Last Person to Fit in the Bus LeetCode Solution

Last Person to Fit in the Bus LeetCode Solution

Problem Statement

Column NameType
person_idint
person_namevarchar
weightint
turnint
Table: Queue

person_id column contains unique values. This table has the information about all people waiting for a bus.
The person_id and turn columns will contain all numbers from 1 to n, where n is the number of rows in the table.
turn determines the order of which the people will board the bus, where turn=1 denotes the first person to board and turn=n denotes the last person to board.
weight is the weight of the person in kilograms.

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 a solution 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 result format is in the following example.

Example 1:
Input:

person_idperson_name weightturn
5Alice2501
4Bob1755
3Alex3502
6John Cena4003
1Winston5006
2Marie2004
Queue table:

Output:

person_name
John Cena

Explanation: The following table is ordered by the turn for simplicity.

Turn IDNameWeightTotal Weight
15Alice250250
23Alex350600
36John Cena4001000 (last person to board)
42Marie2001200 (cannot board)
54Bob175_____
61Winston500_____

1. Last Person to Fit in the Bus LeetCode Solution MySQL

select 
  q1.person_name 
from 
  Queue as q1 
  join Queue as q2 on q1.turn >= q2.turn 
group by 
  q1.turn 
having 
  sum(q2.weight) <= 1000 
order by 
  sum(q2.weight) desc 
limit 
  1;
Scroll to Top