返回介绍

solution / 1200-1299 / 1204.Last Person to Fit in the Bus / README_EN

发布于 2024-06-17 01:03:22 字数 3389 浏览 0 评论 0 收藏 0

1204. Last Person to Fit in the Bus

中文文档

Description

Table: Queue

+-------------+---------+
| Column Name | Type  |
+-------------+---------+
| person_id   | int   |
| person_name | varchar |
| weight    | int   |
| turn    | int   |
+-------------+---------+
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.

 

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.

The result format is in the following example.

 

Example 1:

Input: 
Queue table:
+-----------+-------------+--------+------+
| person_id | person_name | weight | turn |
+-----------+-------------+--------+------+
| 5     | Alice     | 250  | 1  |
| 4     | Bob     | 175  | 5  |
| 3     | Alex    | 350  | 2  |
| 6     | John Cena   | 400  | 3  |
| 1     | Winston   | 500  | 6  |
| 2     | Marie     | 200  | 4  |
+-----------+-------------+--------+------+
Output: 
+-------------+
| person_name |
+-------------+
| John Cena   |
+-------------+
Explanation: The folowing table is ordered by the turn for simplicity.
+------+----+-----------+--------+--------------+
| Turn | ID | Name    | Weight | Total Weight |
+------+----+-----------+--------+--------------+
| 1  | 5  | Alice   | 250  | 250      |
| 2  | 3  | Alex    | 350  | 600      |
| 3  | 6  | John Cena | 400  | 1000     | (last person to board)
| 4  | 2  | Marie   | 200  | 1200     | (cannot board)
| 5  | 4  | Bob     | 175  | ___      |
| 6  | 1  | Winston   | 500  | ___      |
+------+----+-----------+--------+--------------+

Solutions

Solution 1

# Write your MySQL query statement below
SELECT a.person_name
FROM
  Queue AS a,
  Queue AS b
WHERE a.turn >= b.turn
GROUP BY a.person_id
HAVING SUM(b.weight) <= 1000
ORDER BY a.turn DESC
LIMIT 1;

Solution 2

# Write your MySQL query statement below
WITH
  T AS (
    SELECT
      person_name,
      SUM(weight) OVER (ORDER BY turn) AS s
    FROM Queue
  )
SELECT person_name
FROM T
WHERE s <= 1000
ORDER BY s DESC
LIMIT 1;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文