본문 바로가기

ProgramSoliving

프로그래머스 : 보석 쇼핑

반응형
const isTrue = (count, cnt) => {
    for(let i=0;i<cnt;i++) {
        if(count[i] === 0) return false;
    }
    return true;
}

function solution(gems) {
    const len = gems.length;
    const hash = new Map();
    let cnt = 0;
    for(let i=0; i<len; i++) {
        if(!hash.has(gems[i])) {
            hash.set(gems[i], cnt++);   
        }
    }
    
    let count = Array(cnt).fill(0);
    let front = 0;
    let rear = 0;
    let MinRange = 987654321;
    let answer = [];
    
    while(front <= rear) {
        if(isTrue(count, cnt)){
            if(MinRange > rear - front) {
                MinRange = rear - front;
                answer = [front + 1, rear];
            }
            const num = hash.get(gems[front++]);
            count[num]--;
        } else {
            if(rear + 1 > len)
                break;
            const num = hash.get(gems[rear++]);
            count[num]++;
        }
    }
    
    return answer;
}
반응형