홍동이의 성장일기

[LeetCode] 1204. Last Person to Fit in the Bus (누적합계 구하기) 본문

Tool/SQL 코딩테스트 풀이

[LeetCode] 1204. Last Person to Fit in the Bus (누적합계 구하기)

홍동2 2023. 12. 30. 16:02

 

Last Person to Fit in the Bus - LeetCode

Can you solve this real interview question? Last Person to Fit in the Bus - Table: Queue +-------------+---------+ | Column Name | Type | +-------------+---------+ | person_id | int | | person_name | varchar | | weight | int | | turn | int | +-------------

leetcode.com

 

WITH cte_last AS (
    SELECT *
            , SUM(weight) OVER(ORDER BY turn) as total_weight
    FROM queue
    ORDER BY turn
)
SELECT person_name
FROM cte_last
WHERE total_weight <= 1000
ORDER BY total_weight DESC
LIMIT 1

 

 

💡 문제 풀이

 

SELECT *
        , SUM(weight) OVER(ORDER BY turn) as total_weight
FROM queue
ORDER BY turn

 

➡️ SUM OVER을 이용해서 weight의 누적 합계를 구해줍니다.

      turn이 빠른 사람부터 차례대로 더해주기위해 turn을 기준으로 정렬해줍니다.

 

WITH cte_last AS (
    SELECT *
            , SUM(weight) OVER(ORDER BY turn) as total_weight
    FROM queue
    ORDER BY turn
)
SELECT *
FROM cte_last
WHERE total_weight <= 1000

 

➡️ 누적 몸무게가 1000보다 작은 행만 불러옵니다.

 

ORDER BY total_weight DESC
LIMIT 1

 

➡️ 다시 누적 몸무게를 내림차순한 후, 가장 윗 행만 나오게하도록 LIMIT을 해줍니다.

728x90
Comments