Skip to content

Commit f6c3209

Browse files
Last Person to Fit in the Elevator
1 parent 386ca05 commit f6c3209

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Leetcode_1204.sql

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/*
2+
Last Person to Fit in the Elevator
3+
4+
Table: Queue
5+
6+
+-------------+---------+
7+
| Column Name | Type |
8+
+-------------+---------+
9+
| person_id | int |
10+
| person_name | varchar |
11+
| weight | int |
12+
| turn | int |
13+
+-------------+---------+
14+
person_id is the primary key column for this table.
15+
This table has the information about all people waiting for an elevator.
16+
The person_id and turn columns will contain all numbers from 1 to n, where n is the number of rows in the table.
17+
18+
19+
The maximum weight the elevator can hold is 1000.
20+
21+
Write an SQL query to find the person_name of the last person who will fit in the elevator without exceeding the weight limit.
22+
It is guaranteed that the person who is first in the queue can fit in the elevator.
23+
24+
The query result format is in the following example:
25+
26+
Queue table
27+
+-----------+-------------------+--------+------+
28+
| person_id | person_name | weight | turn |
29+
+-----------+-------------------+--------+------+
30+
| 5 | George Washington | 250 | 1 |
31+
| 3 | John Adams | 350 | 2 |
32+
| 6 | Thomas Jefferson | 400 | 3 |
33+
| 2 | Will Johnliams | 200 | 4 |
34+
| 4 | Thomas Jefferson | 175 | 5 |
35+
| 1 | James Elephant | 500 | 6 |
36+
+-----------+-------------------+--------+------+
37+
38+
Result table
39+
+-------------------+
40+
| person_name |
41+
+-------------------+
42+
| Thomas Jefferson |
43+
+-------------------+
44+
45+
Queue table is ordered by turn in the example for simplicity.
46+
In the example George Washington(id 5), John Adams(id 3) and Thomas Jefferson(id 6) will enter the elevator as their
47+
weight sum is 250 + 350 + 400 = 1000. Thomas Jefferson(id 6) is the last person to fit in the elevator because he has the
48+
last turn in these three people.
49+
*/
50+
51+
# MY SOLUTION
52+
SELECT c.person_name
53+
FROM (SELECT a.person_name, SUM(b.weight) AS maximum
54+
FROM (SELECT person_id * 0 AS grouping, person_name, weight, turn
55+
FROM Queue) AS a
56+
INNER JOIN (SELECT person_id * 0 AS grouping, person_name, weight, turn
57+
FROM Queue) AS b
58+
ON a.grouping = b.grouping AND a.turn >= b.turn
59+
GROUP BY a.grouping, a.turn
60+
HAVING maximum <= 1000
61+
ORDER BY a.turn DESC) AS c
62+
LIMIT 1
63+
64+
# SOLUTION by LijianChen
65+
SELECT a.person_name
66+
FROM Queue a
67+
INNER JOIN Queue b
68+
ON a.turn >= b.turn
69+
GROUP BY a.turn
70+
HAVING SUM(b.weight) <= 1000
71+
ORDER BY SUM(b.weight) DESC
72+
LIMIT 1

0 commit comments

Comments
 (0)