[Algorithm] 가장 많이 받은 선물

sooki_m·2024년 4월 15일
1

algorithm

목록 보기
5/5
post-thumbnail

접근 방식

2차원 배열을 만들어 row => 선물을 준 사람, column => 선물을 받은 사람이 되어 서로 주고 받은 선물을 개수를 해당 2차원 배열의 값에서 1씩 더해준다. (같은 사람들끼리 여러 번 선물을 주고 받을 수 있음)

하나의 row의 합은 한 사람이 준 선물의 총 합이고, 하나의 column은 한 사람이 받은 선물의 총 합이다.

reduce로 각각을 더해서 선물 지수를 구해준다.

마지막에 조건에 나온 것처럼 2차원 배열의 값을 먼저 비교하고 같은 경우에만 선물 지수를 비교해서 totalGift 값을 구해주고 전체 배열의 max 값을 리턴하면 정답이다.

정답 코드

function solution(friends, gifts) {
    const map = friends.reduce((acc, cur, idx) => {
        acc[cur] = idx;
        return acc;
    }, {});

    const giftArray = Array.from(new Array(friends.length), () => new Array(friends.length).fill(0));

    for (let gift of gifts) {
        const [a, b] = gift.split(' ');

        giftArray[map[a]][map[b]] = giftArray[map[a]][map[b]] + 1;
    }

    const giftNumber = friends.map((friend, idx) => {
        const give = new Array(friends.length).fill(0).reduce((acc, _, index) => {
            acc += giftArray[idx][index];
            return acc;
        }, 0);
        const receive = new Array(friends.length).fill(0).reduce((acc, _, index) => {
            acc += giftArray[index][idx];
            return acc;
        }, 0);

        return give - receive;
    });

    const totalGift = new Array(friends.length).fill(0);

    for (let i = 0; i < friends.length-1; i++) {
        const provider = friends[i]; // 선물 준 사람
        for (let j = i+1; j < friends.length; j++) {
            const consumer = friends[j]; // 받은 사람
            if (giftArray[i][j] > giftArray[j][i]) {
                totalGift[i]++;
            } else if (giftArray[i][j] < giftArray[j][i]) {
                totalGift[j]++;
            }
            else if (giftArray[i][j] === giftArray[j][i]) {
                if (giftNumber[i] > giftNumber[j]) {
                    totalGift[i]++;
                } else if (giftNumber[i] < giftNumber[j]) {
                    totalGift[j]++;
                }
            }
        }
    }

    return Math.max(...totalGift);
}
profile
머쨍이 개발ing 😎

0개의 댓글