본문 바로가기
알고리즘

[2024 KAKAO WINTER INTERNSHIP] 가장 많이 받은 선물 - java

by 육빔 2024. 7. 24.
728x90
반응형

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

 

프로그래머스

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

programmers.co.kr

 

문제 설명

 

선물하기 기능을 이용한 친구끼리 가장 많이 받을 친구의 선물 수를 구하는 문제

 

풀이

 

처음 보고 난 생각은 2차원 배열에 저장시키고 비교하면서 카운트를 세고 최댓값을 반환하는 형식으로 구현했다.

 

 

import java.util.*;

class Solution {
    public int solution(String[] friends, String[] gifts) {
        Map<String, Integer> map = new HashMap<>();
        
        for(int i=0; i<friends.length; i++){
            map.put(friends[i], i);
        }
        System.out.println(map);
        
        int []index = new int[friends.length];
        int [][] record = new int[friends.length][friends.length];
        
        for(String str : gifts){
            String []cur = str.split(" ");
            index[map.get(cur[0])]++;
            index[map.get(cur[1])]--;
            record[map.get(cur[0])][map.get(cur[1])]++;
            // System.out.println(Arrays.toString(index));
            // System.out.println(Arrays.deepToString(record));
        }
        int ans = 0;
        for (int i = 0; i < friends.length; i++) {
           int cnt = 0;
           for (int j = 0; j < friends.length; j++) {
               if(i == j) continue;
               if (record[i][j] > record[j][i]) cnt++;
               else if (record[i][j] == record[j][i] && index[i] > index[j]) cnt++; 
           }
           ans = Math.max(cnt, ans);
       }
        return ans;
    }
}

 

완성

728x90
반응형