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

后端 未结 9 1553
醉话见心
醉话见心 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:20

    The java version, though Python already showed its functional advantage and beat me:

    private static class Solution {
        BigInteger product;
        String expression;
    }
    
    private static Solution solve(String digits, int multiplications) {
        if (digits.length() < multiplications + 1) {
            return null; // No solutions
        }
        if (multiplications == 0) {
            Solution solution = new Solution();
            solution.product = new BigInteger(digits);
            solution.expression = digits;
            return solution;
        }
        // Position of first '*':
        Solution max = null;
        for (int i = 1; i < digits.length() - (multiplications - 1); ++i) {
            BigInteger n = new BigInteger(digits.substring(0, i));
            Solution solutionRest = solve(digits.substring(i), multiplications - 1);
            n = n.multiply(solutionRest.product);
            if (max == null || n.compareTo(max.product) > 0) {
                solutionRest.product = n;
                solutionRest.expression = digits.substring(0, i) + "*"
                    + solutionRest.expression;
                max = solutionRest;
            }
        }
        return max;
    }
    
    private static void test(String digits, int multiplications) {
        Solution solution = solve(digits, multiplications);
        System.out.printf("%s %d -> %s = %s%n", digits, multiplications,
                solution.expression, solution.product.toString());
    }
    
    public static void main(String[] args) {
        test("1826456903521651", 5);
    }
    

    Output

    1826456903521651 5 -> 182*645*6*903*521*651 = 215719207032420
    

提交回复
热议问题