Making Candies

  • + 0 comments

    100% Javascript solution that should be easy to understand

    function minimumPasses(m, w, p, n) {
        if (n <= p) {
            return Math.ceil(n / (m * w));
        }
        
        let currentDay = 0;
        let candy = 0;
        
        while (candy < n) {
            const remainingDaysWithCurrentProduction = Math.ceil((n - candy) / (m * w));      
            
            const canBuy = Math.floor(candy / p);
            
            if (canBuy === 0) {
                // keep saving until enough for a purchase            
                const i = Math.ceil((p - candy) / (m * w));
                currentDay += i;
                candy += (m * w * i);
                continue;
            }
    
            const total = m + w + canBuy;
            const half = Math.floor(total / 2);
            let mNew = m;
            let wNew = w;
    
            if (m > w){
                mNew = Math.max(m, half);
                wNew = total - mNew;
            } else {
                wNew = Math.max(w, half);
                mNew = total - wNew;
            }
            
            const rest = candy % p;
            const remainingDaysWithIncreasedProduction = Math.ceil((n - rest) / (mNew * wNew));
            
            if (remainingDaysWithCurrentProduction < remainingDaysWithIncreasedProduction) {
                // stop purchasing and produce until done
                return currentDay + remainingDaysWithCurrentProduction;
            }
            
            // purchases machines and workers and continue
            candy = rest;
            m = mNew;
            w = wNew;            
            currentDay += 1;
            candy += (m * w);
        }
        
        return currentDay;
    }