빙응의 공부 블로그

[Programmers]Lv.1 가장 많이 받은 선물 본문

Argorithm

[Programmers]Lv.1 가장 많이 받은 선물

빙응이 2024. 1. 9. 20:13


📝풀이

해당 문제에서 나는 해쉬맵을 사용하였다.

2개의 해쉬맵

  • 선물 지수를 저장하는 해쉬맵
  • 친구별 선물 갯수를 저장하는 해쉬맵

어려운 문제가 아니라서 해쉬맵마다 초기화만 잘 해주면 된다.

 

import java.util.HashMap;

class Solution {
    public int solution(String[] friends, String[] gifts) {
        HashMap<String, Integer> giftScore = new HashMap<>(); // 선물 지수
        HashMap<String, HashMap<String, Integer>> giftCount = new HashMap<>(); // 주고 받은 기록

        // 초기화
        for (String friend : friends) {
            giftScore.put(friend, 0);
            HashMap<String, Integer> friendGiftCount = new HashMap<>();
            for (String friend2 : friends) {
                if (!friend.equals(friend2)) {
                    friendGiftCount.put(friend2, 0);
                }
            }
            giftCount.put(friend, friendGiftCount);
        }

        // 선물 기록 업데이트
        for (String gift : gifts) {
            String[] temp = gift.split(" ");
            HashMap<String, Integer> senderGiftCount = giftCount.get(temp[0]);
            senderGiftCount.put(temp[1], senderGiftCount.get(temp[1]) + 1);
            giftCount.put(temp[0], senderGiftCount);

            // 선물 지수 업데이트
            giftScore.put(temp[0], giftScore.get(temp[0]) + 1);
            giftScore.put(temp[1], giftScore.get(temp[1]) - 1);
        }

        int answer = 0;

        // 친구 간 비교
        for (String friend : friends) {
            int count = 0;
            for (String friend2 : friends) {
                if (!friend.equals(friend2)) {
                    int hasGivenGift = giftCount.get(friend).get(friend2);
                    int hasReceivedGift = giftCount.get(friend2).get(friend);
                    if (hasGivenGift > hasReceivedGift || (hasGivenGift == hasReceivedGift && giftScore.get(friend) > giftScore.get(friend2))) {
                        count++;
                    }
                }
            }
            answer = Math.max(answer, count);
        }

        return answer;
    }
}

 

'Argorithm' 카테고리의 다른 글

[Programmers]Lv.2 요격 시스템  (0) 2024.01.10
[BOJ]1417번 국회의원 선거  (0) 2024.01.10
[Programmers]Lv.1 이상한 문자 만들기  (0) 2024.01.08
[Programmers]Lv.1 비밀지도  (0) 2024.01.03
[Programmers]Lv.1 다트게임  (1) 2024.01.03