목차

프린터

ps
링크programmers.co.kr/…
출처프로그래머스
문제 번호42587
문제명프린터
레벨Level 2
분류

애드혹

시간복잡도O(n)
인풋사이즈n<=100
사용한 언어Python
해결날짜2021/08/12
태그

고득점 Kit - 스택/큐

풀이

코드

"""Solution code for "Programmers 42587. 프린터".

- Problem link: https://programmers.co.kr/learn/courses/30/lessons/42587
- Solution link: http://www.teferi.net/ps/problems/programmers/42587
"""


def solution(priorities, location):
    def dist_from_last_index(index):
        dist = index - last_index
        return dist if dist >= 0 else dist + len(priorities)
    
    priority = priorities[location]
    max_priority = max(priorities)
    indexes_by_priority = [[] for _ in range(max_priority + 1)]
    for i, p in enumerate(priorities):
        indexes_by_priority[p].append(i)
    last_index = 0
    answer = 0
    for p in range(max_priority, priority, -1):
        if not (indexes := indexes_by_priority[p]):
            continue
        answer += len(indexes)
        last_index = max(indexes, key=dist_from_last_index)
    target_dist = dist_from_last_index(location)
    answer += sum(1 for i in indexes_by_priority[priority]
                  if dist_from_last_index(i) <= target_dist)

    return answer