Skip to content

Commit 9a83bc8

Browse files
committed
Create 1204. Last Person to Fit in the Bus.md
1 parent 0b2ec06 commit 9a83bc8

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# 1204. Last Person to Fit in the Bus
2+
```
3+
4+
+-------------+---------+
5+
| Column Name | Type |
6+
+-------------+---------+
7+
| person_id | int |
8+
| person_name | varchar |
9+
| weight | int |
10+
| turn | int |
11+
+-------------+---------+
12+
13+
```
14+
15+
person_id column contains unique values.
16+
This table has the information about all people waiting for a bus.
17+
The person_id and turn columns will contain all numbers from 1 to n, where n is the number of rows in the table.
18+
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.
19+
weight is the weight of the person in kilograms.
20+
21+
22+
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.
23+
24+
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.
25+
26+
Note that only one person can board the bus at any given turn.
27+
28+
## The result format is in the following example.
29+
30+
```table[]
31+
32+
Example 1:
33+
34+
Input:
35+
Queue table:
36+
+-----------+-------------+--------+------+
37+
| person_id | person_name | weight | turn |
38+
+-----------+-------------+--------+------+
39+
| 5 | Alice | 250 | 1 |
40+
| 4 | Bob | 175 | 5 |
41+
| 3 | Alex | 350 | 2 |
42+
| 6 | John Cena | 400 | 3 |
43+
| 1 | Winston | 500 | 6 |
44+
| 2 | Marie | 200 | 4 |
45+
+-----------+-------------+--------+------+
46+
Output:
47+
+-------------+
48+
| person_name |
49+
+-------------+
50+
| John Cena |
51+
+-------------+
52+
Explanation: The folowing table is ordered by the turn for simplicity.
53+
+------+----+-----------+--------+--------------+
54+
| Turn | ID | Name | Weight | Total Weight |
55+
+------+----+-----------+--------+--------------+
56+
| 1 | 5 | Alice | 250 | 250 |
57+
| 2 | 3 | Alex | 350 | 600 |
58+
| 3 | 6 | John Cena | 400 | 1000 | (last person to board)
59+
| 4 | 2 | Marie | 200 | 1200 | (cannot board)
60+
| 5 | 4 | Bob | 175 | ___ |
61+
| 6 | 1 | Winston | 500 | ___ |
62+
+------+----+-----------+--------+--------------+
63+
```
64+
65+
```SQL[]
66+
# Write your MySQL query statement below
67+
# Write your MySQL query statement below
68+
SELECT a.person_name
69+
FROM
70+
Queue AS a,
71+
Queue AS b
72+
WHERE a.turn >= b.turn
73+
GROUP BY a.person_id
74+
HAVING SUM(b.weight) <= 1000
75+
ORDER BY a.turn DESC
76+
LIMIT 1;
77+
```

0 commit comments

Comments
 (0)