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

后端 未结 9 1644
醉话见心
醉话见心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-30 12:06

    This implementation is for @lars.

    from __future__ import (print_function)
    import collections
    import sys
    
    try:
        xrange
    except NameError:  # python3
        xrange = range
    
    
    def max_product(s, n):
        """Return the maximum product of digits from the string s using m
        multiplication operators.
    
        """
        # Guard condition.
        if len(s) <= n:
            return None
    
        # A type for our partial solutions.
        partial_solution = collections.namedtuple("product",
                                                  ["value", "expression"])
    
        # Initialize the best_answers dictionary with the leading terms
        best_answers = {}
        for i in xrange(len(s)):
            term = s[0: i+1]
            best_answers[i+1] = partial_solution(int(term), term)
    
        # We then replace best_answers n times.
        for prev_product_count in [x for x in xrange(n)]:
            product_count = prev_product_count + 1
            old_best_answers = best_answers
            best_answers = {}
            # For each position, find the best answer with the last * there.
            for position in xrange(product_count+1, len(s)+1):
                candidates = []
                for old_position in xrange(product_count, position):
                    prior_product = old_best_answers[old_position]
                    term = s[old_position:position]
                    value = prior_product.value * int(term)
                    expression = prior_product.expression + "*" + term
                    candidates.append(partial_solution(value, expression))
                # max will choose the biggest value, breaking ties by the expression
                best_answers[position] = max(candidates)
    
        # We want the answer with the next * going at the end of the string.
        return best_answers[len(s)]
    
    print(max_product(sys.argv[1], int(sys.argv[2])))
    

    Here is a sample run:

    $ python mult.py 99287 2
    product(value=72036, expression='9*92*87')
    

    Hopefully the logic is clear from the implementation.

提交回复
热议问题