[Leet code] 1204. Last Person to Fit in the Bus
๐ข ๋ณธ ํฌ์คํ ์ ํ์ฉ๋๋ ๊ธฐ๋ณธ ๋ฌธ์ ๋ฐ ์๋ฃ ์ถ์ฒ๋
๋ฆฌํธ์ฝ๋ Problems, https://leetcode.com/problemset/all/์์ ๋ฐํ๋๋ค.
โ๋ฌธ์
https://leetcode.com/problems/last-person-to-fit-in-the-bus/description/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Table : Queue
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.
โ ํ์ด
๋ฌธ์ ์๊ตฌ์ฌํญ
๋ฒ์ค๋ฅผ ํ๋ ค๋ ์ฌ๋๋ค์ด ์ค์ ์ ์๋๋ฐ ๋ฒ์ค๊ฐ ํ์น ๋ฌด๊ฒ ์ ํ์ด ์์ด 1000kg๋ฅผ ์ด๊ณผํ ๊ฒฝ์ฐ ๋์ด์ ๊ณ ๊ฐ์ด ํ์นํ ์ ์๋ค. ์ด ๋ฒ์ค์ ํ์นํ ์ ์๋ ๋ง์ง๋ง person_name์ ๊ตฌํ๋ ๋ฌธ์ ์ด๋ค.
ํ์น ์์(turn)๋ง๋ค ํ์นํ ์ฌ๋์ ๋ํ ์ด ๋ฌด๊ฒ๋ฅผ ํ์ธํด์ผ ํ๋ฏ๋ก
โ ์๋์ฐ ํจ์ sum()์ ์ฌ์ฉํด์ ํ์น ์์์ ๋ฐ๋ฅธ ๋์ ๋ฌด๊ฒํฉ์ ๊ตฌํด์ฃผ๋ ํ ์ด๋ธ์ ๋ง๋ ํ
โก ๋ฐ์ดํฐ ์ ๋ ฌ์ ํ์น ์์์ ๋ด๋ฆผ์ฐจ์์ผ๋ก ์ญ์ ๋ ฌํด์ฃผ๊ณ
โข < โก> ๊ฒฐ๊ณผ์ ๋ํด ๋ฌด๊ฒํฉ์ด 1000์ ์ด๊ณผํ์ง ์๋ where์กฐ๊ฑด์ ๋ถ์ฌํ์ฌ ๊ฐ์ฅ ์ฒซ๋ฒ์งธ ์ถ๋ ฅ๋๋ person_name์ ์ถ๋ ฅํด์ฃผ์๋ค.
SELECT person_name
FROM (
SELECT *, SUM(weight) OVER (ORDER BY turn) AS limit_wg
FROM Queue
ORDER BY turn DESC
) Q
WHERE limit_wg <= 1000
LIMIT 1