프로그래머스/lv.1

가장 많이 받은 선물

bingual 2024. 2. 1. 21:36
반응형

https://school.programmers.co.kr/learn/courses/30/lessons/258712

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제풀이

카카오 2024년 인턴쉽 문제로 정답률 22%이다. 레벨 1 치고는 난이도가 높은편이다.
전부 해시를 활용해서 풀었다. 선물 지수와 관련된 로직을 짜는게 핵심이다.

from collections import defaultdict


def solution(friends, gifts):
    answer = 0
    # 선물을 주고받은 기록
    history = {
        friend: {"gift": defaultdict(int), "received": defaultdict(int), "rank": 0}
        for friend in friends
    }
    set_friends = set(friends)

    # 선물 지수
    def history_index(friend):
        x = sum(history[friend]["gift"].values())
        y = sum(history[friend]["received"].values())
        return x - y

    # 선물을 주고받지 않은 사람
    def history_difference(friend):
        y = set(
            list(history[friend]["gift"]) + list(history[friend]["received"]) + [friend]
        )
        return set_friends - y

    # 선물 기록 갱신
    for gift in gifts:
        giver, recipient = gift.split()
        history[giver]["gift"][recipient] += 1
        history[recipient]["received"][giver] += 1

    # 받은 선물 계산
    for friend in friends:
        pivot_index = history_index(friend)
        pivot_difference = history_difference(friend)

        # 선물을 주고받은 기록이 하나도 없을때 처리
        if pivot_difference:
            for name in pivot_difference:
                if pivot_index > history_index(name):
                    history[friend]["rank"] += 1

        # 선물을 주고받은 기록이 있을때 처리
        for giver, give_cnt in history[friend]["gift"].items():
            if giver in history[friend]["received"]:
                received_cnt = history[friend]["received"][giver]
                if give_cnt > received_cnt or (
                    give_cnt == received_cnt and pivot_index > history_index(giver)
                ):
                    history[friend]["rank"] += 1
            else:
                history[friend]["rank"] += 1

        # 가장 많이 선물받은 값 저장
        answer = max(answer, history[friend]["rank"])

    return answer

 

 

레벨 1단계의 모든 문제를 풀었다. 프로그래머스는 같은 레벨이라해도 상위 레벨 보다 어려운 경우도 많고 난이도가 천차만별인데 특히 카카오 문제가 그렇다. 다음은 레벨 2단계를 all solved 할 시간이다.