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

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

    I found the above DP solution helpful but confusing. The recurrence makes some sense, but I wanted to do it all in one table without that final check. It took me ages to debug all the indices, so I've kept some explanations.

    To recap:

    1. Initialize T to be of size N (because digits 0..N-1) by k+1 (because 0..k multiplications).
    2. The table T(i,j) = the greatest possible product using the i+1 first digits of the string (because of zero indexing) and j multiplications.
    3. Base case: T(i,0) = digits[0..i] for i in 0..N-1.
    4. Recurrence: T(i,j) = maxa(T(a,j-1)*digits[a+1..i]). That is: Partition digits[0..i] in to digits[0..a]*digits[a+1..i]. And because this involves a multiplication, the subproblem has one fewer multiplications, so search the table at j-1.
    5. In the end the answer is stored at T(all the digits, all the multiplications), or T(N-1,k).

    The complexity is O(N2k) because maximizing over a is O(N), and we do it O(k) times for each digit (O(N)).

    public class MaxProduct {
    
        public static void main(String ... args) {
            System.out.println(solve(args[0], Integer.parseInt(args[1])));
        }
    
        static long solve(String digits, int k) {
            if (k == 0)
                return Long.parseLong(digits);
    
            int N = digits.length();
            long[][] T = new long[N][k+1];
            for (int i = 0; i < N; i++) {
                T[i][0] = Long.parseLong(digits.substring(0,i+1));
                for (int j = 1; j <= Math.min(k,i); j++) {
                    long max = Integer.MIN_VALUE;
                    for (int a = 0; a < i; a++) {
                        long l = Long.parseLong(digits.substring(a+1,i+1));
                        long prod = l * T[a][j-1];
                        max = Math.max(max, prod);
                    }
                    T[i][j] = max;
                }
            }
            return T[N-1][k];
        }
    }
    

提交回复
热议问题