Given a string of numbers and a number of multiplication operators, what is the highest number one can calculate?

后端 未结 9 1554
醉话见心
醉话见心 2021-01-30 11:22

This was an interview question I had and I was embarrassingly pretty stumped by it. Wanted to know if anyone could think up an answer to it and provide the big O notation for it

9条回答
  •  一向
    一向 (楼主)
    2021-01-30 12:06

    I am assuming here that the required number m of multiplication operators is given as part of the problem, along with the string s of digits.

    You can solve this problem using the tabular method (aka "dynamic programming") with O(m |s|2) multiplications of numbers that are O(|s|) digits long. The optimal computational complexity of multiplication is not known, but with the schoolbook multiplication algorithm this is O(m |s|4) overall.

    (The idea is to compute the answer for each subproblem consisting of a tail of the string and a number m′ ≤ m. There are O(m |s|) such subproblems and solving each one involves O(|s|) multiplications of numbers that are O(|s|) digits long.)

    In Python, you could program it like this, using the @memoized decorator from the Python decorator library:

    @memoized
    def max_product(s, m):
        """Return the maximum product of digits from the string s using m
        multiplication operators.
    
        """
        if m == 0:
            return int(s)
        return max(int(s[:i]) * max_product(s[i:], m - 1)
                   for i in range(1, len(s) - m + 1))
    

    If you're used to the bottom-up form of dynamic programming where you build up a table, this top-down form might look strange, but in fact the @memoized decorator maintains the table in the cache property of the function:

    >>> max_product('56789', 1)
    51102
    >>> max_product.cache
    {('89', 0): 89, ('9', 0): 9, ('6789', 0): 6789, ('56789', 1): 51102, ('789', 0): 789}
    

提交回复
热议问题