C++ O(N2) DP solution


  • 0
    P
    class Solution {
    public:
        
        int integerBreak(int n) {
            std::vector<int> productMap(n+1, 0);
            productMap[1] = productMap[2] = 1;
            return integerBreak(n, productMap);
        }
        
        int integerBreak(int n, std::vector<int>& productMap) {
            if(productMap[n] != 0){
                return productMap[n];
            }
            int maxP = 1;
            for(int i=1; i<= n-1; i++){
                int prev = integerBreak(n-i, productMap);
                int curr = std::max(i*(n-i), i*prev);
                maxP = std::max(curr, maxP);
            }
            productMap[n] = maxP;
            return maxP;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.