본문 바로가기
취준/코팅 테스트

[LeetCode] - 1204. Last Person to Fit in the Bus

by 소복소복뚜벅뚜벅 2024. 4. 6.
문제
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 limi

 

Table 

 

" 순서대로 버스를 탔을 때, 몸무게가 1000kg 이 넘을 때, 하차해야 한다. 이때, 마지막으로 탈 수 있는 사람의 이름을 확인하시오." 

 

정답코드 

SELECT person_name 
FROM(
    SELECT *
        , SUM(weight) OVER (ORDER BY turn) AS sum_weight         
    FROM Queue
    ) t
WHERE sum_weight <= 1000 
ORDER BY sum_weight DESC
LIMIT 1

 

풀이과정

 

1. 먼저 SUM() OVER() 윈도우 함수를 활용하여 turn 별로 누적 몸무게의 합을 구한다. 

** SUM() OVER( ORDER BY) 는 누적합계 합을 구할 수 있는 윈도우 함수 

SELECT *
        , SUM(weight) OVER (ORDER BY turn) AS sum_weight         
FROM Queue

 

 

2. sum_weight 값이 1000 이하인 person_name을 구한다. 

SELECT person_name 
FROM(
    SELECT *
        , SUM(weight) OVER (ORDER BY turn) AS sum_weight         
    FROM Queue
    ) t
WHERE sum_weight <= 1000

 

3. ORDER BY를 활용하여 내림차순으로 정렬한 후, 가장 첫번째 행의 값을 선택한다. (1000kg 되기 직전의 사람) 

SELECT person_name 
FROM(
    SELECT *
        , SUM(weight) OVER (ORDER BY turn) AS sum_weight         
    FROM Queue
    ) t
WHERE sum_weight <= 1000 
ORDER BY sum_weight DESC
LIMIT 1