Leetcode Daily Problem - 4 Jan 2023

Leetcode Daily Problem - 4 Jan 2023

Minimum Rounds to Complete All Tasks - Javascript Algorithms

Problem Name - Minimum Rounds to Complete All Tasks

Problem Link - https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/description/

Solution 1

/**
 * @param {number[]} tasks
 * @return {number}
 */
var minimumRounds = function(tasks) {
    const cnt = new Map();

    tasks.forEach((task) => {
        cnt.set(task, (cnt.get(task) || 0) +1);
    })

    let ans = 0;
    // traverse map 

    for(let [_, value] of cnt) {
        let maxN = parseInt(value/3);

        let currAns = value;
        let flag = false;
        for(let n = 0; n<=maxN ; n++){
            let rem = value - 3*n;

            if (rem%2==0){
                currAns = Math.min(currAns, n + parseInt(rem/2));
                flag=true;
            }
        }

        if (!flag) return -1;

        ans += currAns;
    }

    return ans;
};

Solution 2

/**
 * @param {number[]} tasks
 * @return {number}
 */
var minimumRounds = function(tasks) {
    const cnt = new Map();

    tasks.forEach((task) => {
        cnt.set(task, (cnt.get(task) || 0) +1);
    })

    let ans = 0;
    // traverse map 

    for(let [_, value] of cnt) {
        // As we can always divide value = 3*n + 2*m form except when value === 1
        if(value === 1) return -1;
        // now we have to minimize rounds that means increase n
        // there are three conditions possible for remainder by 3 -> 0, 1 , 2

        // if remainder 0 -> value/3 will be ans 
        // if remainder 1 -> then (value - 3)/3 + (3 + 1) /2 will be ans
        // if remainder 2 -> then value/3 + 1 will be ans 

        const remainder = value%3;

        if(remainder === 0) ans += parseInt(value/3);
        else if (remainder === 1) ans += parseInt((value -3)/3 + 2);
        else ans += parseInt(value /3) + 1;
    }

    return ans;
};