[코드카타] SQL 50 Last Person to Fit in the Bus

Data_Student·2024년 11월 27일
0

코드카타

목록 보기
59/82

[코드카타] SQL 50 Last Person to Fit in the Bus

50. Last Person to Fit in the Bus
https://leetcode.com/problems/last-person-to-fit-in-the-bus/submissions/1463704752/

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.
with temp as (
    select turn, person_id, person_name, weight, 
    sum(weight) over(order by turn) total_weight
    from Queue
    group by turn
    order by turn
)
select person_name
from temp
where total_weight = 1000 
or total_weight = (select max(total_weight) from temp where total_weight <= 1000)
누적합 구하는 법 : sum(col1) over(order by 기준col)
where 조건절에 전체 무게가 1000 이거나 1000보다 작을 경우 누적무게가 최대인 사람 이름 구하기 = 마지막 탑승 인원
+ 최대값을 구하는 다른 방법
WHERE weight_sum <= 1000
ORDER BY turn DESC LIMIT 1;

0개의 댓글