Making Candies

  • + 0 comments

    Solution in Python 3

    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    #
    # Complete the 'minimumPasses' function below.
    #
    # The function is expected to return a LONG_INTEGER.
    # The function accepts following parameters:
    #  1. LONG_INTEGER m
    #  2. LONG_INTEGER w
    #  3. LONG_INTEGER p
    #  4. LONG_INTEGER n
    #
    
    def checkIfMidPassesPossible(m, w, p, n, rounds):
        candies = 0
        while rounds > 0:
            if m * w >= n:
                return True
            remaining_candies = n - candies
            needed_rounds = math.ceil(remaining_candies / (m * w))
            if needed_rounds <= rounds:
                return True
            if candies < p:
                rounds_needed_to_buy = math.ceil((p - candies) / (m * w))
                if rounds_needed_to_buy >= rounds:
                    return False
                rounds -= rounds_needed_to_buy
                candies += rounds_needed_to_buy * m * w
            candies -= p
            if m <= w:
                m += 1
            else:
                w += 1
        return False
    
    def minimumPasses(m, w, p, n):
        #Write your code here
        if p > n:
            return math.ceil(n / (m * w))
        low, high = 1, 10**12
        while low < high:
            mid = (low + high) // 2
            if checkIfMidPassesPossible(m, w, p, n, mid):
                high = mid
            else:
                low = mid + 1
        return low
    
    if __name__ == '__main__':
        fptr = open(os.environ['OUTPUT_PATH'], 'w')
    
        first_multiple_input = input().rstrip().split()
    
        m = int(first_multiple_input[0])
    
        w = int(first_multiple_input[1])
    
        p = int(first_multiple_input[2])
    
        n = int(first_multiple_input[3])
    
        result = minimumPasses(m, w, p, n)
    
        fptr.write(str(result) + '\n')
    
        fptr.close()