기기

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

CS/알고리즘 풀이

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

notEmpty 2024. 6. 14. 20:04

 

 

해결과정

1. 가공할 데이터

  • 모든 친구 A에 대해
    • A가 모든 모든 친구와 선물한 개수 
      • Map<String, Map<String, Integer>>
    • A의 선물 지수
      • Map<String, Integer>

2. 로직 수행

 

문제 설명 그대로 로직 수행하면 된다.

- A, B 기록 유무는 A가 B한테 준 선물과 B가 A한테 준 선물이 모두 0인 경우. 

따라서 A, B가 서로한테 준 선물이 동일한 경우에 포함된다. 

- A give는 A가 B에게 선물한 개수 

 

주의

목표가 제일 많이 선물받은 경우를 구해야하는 것이다. 

따라서 친구 데이터 이중 루프를 돌때, 매번 A -> B 선물, B -> A 선물을 체크하면 출력은 답의 2배가 된다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
 
public class Programmers258712 {
    public static void main(String[] args) {
        String[] friends = new String[] {"a""b""c"};
        String[] gifts = new String[] {"a b""b a"};
        var score = new HashMap<String, Integer>();
 
        // 데이터 가공
        var giveMap = new HashMap<String, Map<String, Integer>>();
 
        for(String f : friends) {
            score.put(f, 0);
            for(String r : friends) {
                if(f.equals(r)) {
                    continue;
                }
                giveMap.putIfAbsent(f, new HashMap<String, Integer>());
                giveMap.get(f).put(r, 0);
            }
        }
 
        for(String str : gifts) {
            String[] gg = str.split(" ");
            String giver = gg[0];
            String rcv = gg[1];
 
            var m = giveMap.get(giver);
            m.put(rcv, m.getOrDefault(rcv, 0+ 1);
 
            score.put(giver, score.getOrDefault(giver, 0+ 1);
            score.put(rcv, score.getOrDefault(rcv, 0- 1);
        }
 
        // 로직
        var next = new HashMap<String, Integer>();
        for(String f : friends) {
            next.put(f, 0);
 
            for(String r : friends) {
                if(f.equals(r)) {
                    continue;
                }
 
                int give1 = giveMap.get(f).get(r);
                int give2 = giveMap.get(r).get(f);
 
                if(give1 == give2) {
                    if(score.get(f) == score.get(r)) {
                        continue;
                    } else if (score.get(f) > score.get(r)) {
                        next.put(f, next.getOrDefault(f, 0+ 1);
//                        next.put(r, next.getOrDefault(r, 0) - 1);
                    }
                } else {
                    if(give1 > give2) {
                        next.put(f, next.getOrDefault(f, 0+ 1);
//                        next.put(r, next.getOrDefault(r, 0) - 1);
                    }
                }
            }
        }
 
        System.out.println(Collections.max(next.values()));
    }
}
 
cs

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