Making Candies

  • + 0 comments

    Time Complexity O(log n) Space Complexity O(1)

    from math import ceil
    
    def minimumPasses(m, w, p, n):
        min_turns = ceil(n/(m*w))  # min turns without ever buying more workers or machines
        if p > n:
            return min_turns
        turn = 0
        candies = 0
        while candies < n:
            # skip to next turn with buying opportunity
            skip_turns = max([ceil((p - candies) / (m*w)), 1])
            turn += skip_turns
            if turn > min_turns:
                # no reason to continue buying the best strategy is to just save from last min_turn calc
                return min_turns
            candies += m*w * skip_turns
            if candies >= p:
                # get new machines
                new_machines = candies // p
                candies -= new_machines * p
                diff = m-w
                # try to balance workers and machines
                if diff > 0:
                    w_buy = min(new_machines, diff)
                    w += w_buy
                    new_machines -= w_buy
                else:
                    m_buy = min(new_machines, abs(diff))
                    m += m_buy
                    new_machines -= m_buy
                # split remainder after balancing and buy half workers and half machines
                w_buy = new_machines // 2
                w += w_buy
                m += new_machines - w_buy
            # check how long till goal without buying anything
            min_turns = min(ceil((n-candies)/(m*w))+turn, min_turns)
        return turn