simple Javascript solution


  • 0
    1
    /**
     * @param {character[]} tasks
     * @param {number} n
     * @return {number}
     */
    var leastInterval = function(tasks, n) {
        
        // create a map of task type to remaining count
        // e.g. { A: 3, B: 3 }
        var taskCounts = {};
        tasks.forEach(function (task) {
            if (taskCounts[task]) {
                taskCounts[task] += 1;
            } else {
                taskCounts[task] = 1;
            }
        });
        
        // create a map of number of ticks before task type can be run again
        // e.g. { A: 2, B: 0 }
        var cooldowns = {};
        Object.keys(taskCounts).forEach(function (type) {
            cooldowns[type] = 0;
        });
        
        var numCycles = 0;
        while (Object.keys(taskCounts).length > 0) {
            
            // choose a task whose type has the highest remaining count
            var nextTaskType = undefined; // needs to be explicitly cleared
            var maxCountFound = 0;
            Object.keys(taskCounts).forEach(function (type) {
                if (cooldowns[type] === 0 && taskCounts[type] > maxCountFound) {
                    nextTaskType = type;
                    maxCountFound = taskCounts[type];
                }
            });
            
            if (nextTaskType) {
                --taskCounts[nextTaskType];
                if (taskCounts[nextTaskType] === 0) {
                    delete taskCounts[nextTaskType];
                    delete cooldowns[nextTaskType];
                } else {
                    // add 1 since all cooldowns will be decremented after this
                    cooldowns[nextTaskType] = n + 1;
                }
            }
            
            // process the cooldowns
            Object.keys(cooldowns).forEach(function (taskType) {
                if (cooldowns[taskType] > 0) {
                    --cooldowns[taskType];
                }
            });
            
            ++numCycles;
        }
        return numCycles;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.