[프로그래머스] 2024 KAKAO WINTER INTERSHIP | 가장 많이 받은 선물

Gaanii·2024년 10월 15일
1

Problem Solving

목록 보기
37/210
post-thumbnail

아래 프로그래머스 로고를 클릭하면 해당 문제로 이동합니다 😀



풀이과정


그냥 직관적으로만 생각해봤다.
A가 B에게 준 선물 개수, B가 A에게 받은 선물 개수를 send_gifts_cnt, receive_gifts_cnt에 넣어놨다.
문제의 입출력 예시 #1에 대해서는 다음과 같이 출력될것이다.

>>> send_gifts_cnt
[[0, 0, 2, 0], [3, 0, 0, 0], [1, 1, 0, 0], [1, 0, 0, 0]]

>>> receive_gifts_cnt
[[0, 3, 1, 1], [0, 0, 1, 0], [2, 0, 0, 0], [0, 0, 0, 0]]

반복문은 send_gifts_cnt를 돌건데 이 때 선물점수를 체크해야해서 각 친구의 선물 점수를 gift_grade[i] = sum(send_gifts_cnt[i]) - sum(receive_gifts_cnt[i])로 저장해두자.

send_gifts_cnt 리스트를 돌면서 [i][j]요소와 [j][i]요소의 대소를 비교한다.

  • Case 1: send_gifts_cnt[i][j] < send_gifts_cnt[j][i]
    i번째 친구한테 선물을 하나 주자. i번 친구가 j번친구에게 선물을 더 많이 줬다.

  • Case 2: send_gifts_cnt[i][j] == send_gifts_cnt[j][i]
    이 때는 i 친구랑 j 친구의 선물 점수를 비교해야한다. 그래서 i번째 친구가 크다면 i번 친구에게 선물을 하나 주자.

위 두가지 경우에서 j가 큰 경우를 확인하지 않는 이유는 ?
어차피 for문으로 리스트를 돌고 j가 큰 경우도 뒤에 가서 결국 돌게 되어있다 ... 그래서 선물이 중복되어 들어갈까봐 그냥 아예 미뤄버렸다.

코드


def solution(friends, gifts):
    send_gifts_cnt = [[0] * len(friends) for _ in range(len(friends))]
    receive_gifts_cnt = [[0] * len(friends)  for _ in range(len(friends))]
    gift_grade = [0] * len(friends)
    total_gift_cnt = [0] * len(friends)

    for gift in gifts:
        sender, receiver = gift.split()
        send_gifts_cnt[friends.index(sender)][friends.index(receiver)] += 1
        receive_gifts_cnt[friends.index(receiver)][friends.index(sender)] += 1

    print(send_gifts_cnt)
    print(receive_gifts_cnt)

    for i in range(len(gift_grade)):
        gift_grade[i] = sum(send_gifts_cnt[i]) -  sum(receive_gifts_cnt[i])

    for i in range(len(send_gifts_cnt)):
        for j in range(len(send_gifts_cnt[i])):
            if send_gifts_cnt[i][j] > send_gifts_cnt[j][i]:
                total_gift_cnt[i] += 1
            elif send_gifts_cnt[i][j] == send_gifts_cnt[j][i]:
                if gift_grade[i] > gift_grade[j]:
                    total_gift_cnt[i] += 1

    answer = max(total_gift_cnt)
    return answer


결과


정답

0개의 댓글