Last Person to Fit in the Bus - LeetCode

Pepzera·2026년 2월 3일

SQL코딩테스트

목록 보기
12/18

Last Person to Fit in the Bus 문제

출처 : LeetCode Last Person to Fit in the Bus

Table

Column NameType
person_idint
person_namevarchar
weightint
turnint

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.

Q.

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.
Note that only one person can board the bus at any given turn.
The result format is in the following example.


질문

1) 버스에 turn 1부터 사람을 태우되, 탑승한 사람들의 누적 몸무게 합이 1000kg을 넘지 않는 선에서 계속 태웁니다.

2) 그 때, 마지막으로 탑승 가능한 사람의 이름(person_name)을 구하라는 문제입니다.

내 답안 📕

WITH check_table AS (
    SELECT *
         , SUM(weight) OVER (ORDER BY turn) AS weight_sum
    FROM Queue
)

SELECT person_name
FROM check_table AS ct
WHERE ct.weight_sum <= 1000
ORDER BY ct.weight_sum DESC
LIMIT 1;

0개의 댓글