😎풀이

  1. 빈도 확인
  2. 빈도 기준 내림차 순 정렬
  3. 요소 확인하며, 가장 많은 요소부터 최대한 많이 사용
  4. 빈도에 따른 재정렬
  5. 사용 가능한 요소 없을 경우 idle로 처리
  6. 전체 스케쥴 수 반환
function leastInterval(tasks: string[], n: number): number {
    const frequent = new Map<string, number>()
    for(const char of tasks) {
        frequent.set(char, (frequent.get(char) ?? 0) + 1)
    }
    let sorted = [...frequent].toSorted((a, b) => b[1] - a[1])
    const history = []
    for(let i = 1; ; i++) {
        if(frequent.size === 0) break
        for(let i = 0; i < sorted.length; i++) {
            const [char] = sorted[i]
            if(!frequent.has(char)) continue
            const lastIdx = history.lastIndexOf(char)
            if(lastIdx !== -1 && lastIdx + n >= history.length) continue
            history.push(char)
            const curFreq = frequent.get(char)
            if(curFreq === 1) frequent.delete(char)
            else frequent.set(char, curFreq - 1)
            sorted = [...frequent].toSorted((a, b) => b[1] - a[1])
            break
        }
        while(history.length < i) {
            history.push('idle')
        }
    }
    return history.length
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글