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

riassuc·2024년 1월 28일

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

function solution(friends, gifts) {
    const len = friends.length;
    
    const init = friends.reduce(([i1, i2], cur, idx) => {
        for (let i = idx + 1; i < len; i++) {
            i1[`${cur} ${friends[i]}`] = 0;
        }
        
        i2[cur] = 0;
        
        return [i1, i2];
    }, [{}, {}]);
    
    const [hash, points] = gifts.reduce(([acc, points], key) => {
        const [a, b] = key.split(' ');
        const minusKey = `${b} ${a}`;
        const cond = acc[key] || acc[key] === 0;
        
        if (cond) {
            acc[key]++;
        } else {
            acc[minusKey]--;
        }
        
        points[a]++;
        points[b]--;
        
        return [acc, points];
    }, init);
    
    const map = Object.entries(hash).reduce((acc, [key, val]) => {
        const [a, b] = key.split(' ');
        let flag = null;
        
        if (val === 0) {
            const gap = points[a] - points[b];
            
            if (gap > 0) {
                flag = a;
            } else if (gap < 0) {
                flag = b;
            }
        }
        
        if (val > 0 || flag === a) {
            acc.set(a, acc.get(a) + 1 || 1);
        } else if (val < 0 || flag === b) {
            acc.set(b, acc.get(b) + 1 || 1);
        }
        
        return acc;
    }, new Map());
    
    return map.size ? Math.max(...map.values()) : 0;
}
profile
riassuc

0개의 댓글