Algorithm

[python] HackerRank - Climbing the Leaderboard

khakhalog 2023. 5. 18. 00:08

문제

https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem?isFullScreen=true#! 

 

Climbing the Leaderboard | HackerRank

Help Alice track her progress toward the top of the leaderboard!

www.hackerrank.com


접근

ranked는 내림차순, player는 오름차순인게 문제 풀이 핵심.

ranked의 뒤부터 (가장 작은 점수부터) player의 앞부터 (가장 작은 점수부터) 비교하면 비교 횟수를 최소로 줄일 수 있다.

반복문 안에서 현재 player가 위치할 인덱스를 찾아주는 과정을 반복하면 ranked 배열에서 지나친 점수에 대해 다시 비교할 필요가 없기 때문.

마지막에 idx + 2 해준 이유는 idx가 0부터 시작(+1) , player가 위치할 인덱스(+1) 를 더해줘야하기 때문


코드

def solution(ranked, player):
    queue = sorted(set(ranked), reverse=True)
    idx = len(queue) - 1
    ans = []

    for p in player:
        while queue[idx] <= p and idx >= 0:
            idx -= 1
        if idx < 0:
            ans.append(1)
            continue
        ans.append(idx + 2)
    return ans