[프로그래머스] 가장 많이 받은 선물

Seohyun·2024년 8월 30일
0

알고리즘

목록 보기
25/36

문제 링크

def solution(friends, gifts):
    answer = [0] * len(friends)
    
    gift_tot = {}
    gift_mat = [[0] * len(friends) for _ in range(len(friends))]
    
    for g in gifts:
        gave, got = g.split(' ')
        row, col = friends.index(gave), friends.index(got)
        gift_mat[row][col] += 1
    for f in range(len(friends)):
        gave_sum = sum(gift_mat[f])
        got_sum = sum([gift_mat[col][f] for col in range(len(friends))])
        gift_tot[friends[f]] = gave_sum - got_sum
        
    for f in range(len(friends)):
        for f1 in range(len(friends)):
            if gift_mat[f][f1] > gift_mat[f1][f]:
                answer[f] += 1
            elif gift_mat[f][f1] == gift_mat[f1][f]:
                if gift_tot[friends[f]] > gift_tot[friends[f1]]:
                    answer[f] += 1
            
    return max(answer)

처음에는 gift_mat를 이중 딕셔너리로 해서 썼는데 중간에 헷갈려서 2차원배열로 변경했다... gift_mat은 각 friend가 주고받은 선물 기록이고, gift_tot은 각 friend의 선물지수를 저장하는 딕셔너리다.

선물기록 gift에서 "A, B"쌍을 gift_mat의 행과 열로 사용해 선물기록을 테이블처럼 저장했다. 이를 토대로 gift_tot을 완성하고, 기준에 따라 각 friend가 받을 선물 개수를 구했다.

profile
Hail hamster

0개의 댓글