[ 알고리즘 ] LeetCode 2173. Longest Winning Streak

이주 weekwith.me·2022년 6월 21일
0

알고리즘

목록 보기
18/73
post-thumbnail

블로그를 이전 중이라 완료되기 전까지는 벨로그에 작성할 계획입니다.
이후 모든 글은 https://weekwith.me 에 작성 예정이니 다른 글이 궁금하시다면 해당 링크를 통해 방문해주세요.

본 글은 [ LeetCode ] 2173. Longest Winning Streak을 풀고 작성한 글입니다.

문제

테이블

Table: Matches

+-------------+------+
| Column Name | Type |
+-------------+------+
| player_id   | int  |
| match_day   | date |
| result      | enum |
+-------------+------+
(player_id, match_day) is the primary key for this table.
Each row of this table contains the ID of a player, the day of the match they played, and the result of that match.
The result column is an ENUM type of ('Win', 'Draw', 'Lose').

요구사항

The winning streak of a player is the number of consecutive wins uninterrupted by draws or losses.

Write an SQL query to count the longest winning streak for each player.

Return the result table in any order.

The query result format is in the following example.

풀이

접근법

player_id 필드를 기준으로 행번호와 result 필드의 값이 Win 인 경우의 누적 합을 빼준 차이가 동일한 경우가 결국 연속된 승리라 할 수 있다. 따라서 이를 기준으로 GROUP BY 구를 통해 묶어주고 그 중에서 가장 큰 값을 반환하면 된다.

이때 한번도 승리한 경우가 없는 경우에 대해서도 별도로 처리 해줘야 하기 때문에 player_id 필드만 따로 뺀 테이블에 LEFT JOIN 구를 활용하여 NULL 값인 경우 IFNULL 함수를 사용해 0 으로 변환해준다.

나의 풀이

접근법을 토대로 문제를 해결하면 아래와 같다.

SELECT
    player_id,
    IFNULL(longest_streak, 0) AS longest_streak
FROM (
    SELECT DISTINCT player_id
    FROM Matches
) AS Players
LEFT JOIN (
    SELECT
        DISTINCT player_id,
        MAX(COUNT(match_day)) OVER(PARTITION BY player_id) AS longest_streak
    FROM (
        SELECT
            player_id,
            match_day,
            result,
            (
                CAST(ROW_NUMBER() OVER(PARTITION BY player_id ORDER BY match_day ASC) AS UNSIGNED)
                -
                CAST(COUNT(IF(result = 'Win', 1, NULL)) OVER(PARTITION BY player_id ORDER BY match_day ASC) AS UNSIGNED)
            ) AS diff
        FROM Matches
    ) AS ConsecutiveWinnings
    WHERE result = 'Win'
    GROUP BY player_id, diff
) AS LongestStreaks
USING (player_id);
profile
Be Happy 😆

0개의 댓글