Python DP solution with explanation


  • 0
    L

    dp[i]: the maximum product for integer i

    For integer n, n = 1 + (n-1) = 2 + (n-2) = ... = j + (n-j) = ... = n-2 + (2)

    So dp[n] = 1 * dp[n-1] or 2 * dp[n-2] or ... or j * dp[n-j] or (n-2) * dp[2], and we just need to get the maximum product among all the possibilities.

    Wait, dp[i] means there will be a break for integer i, and it is also possible there is no break for i. After considering this, we correct the state function as follows.

    dp[n] = 1 * max(dp[n-1], n-1) or 2 * max(dp[n-2], n-2) or ... or j * max(dp[n-j], n-j) or (n-2) * max(dp[2], 2)

    Finally we get the state dp[n] = max(j * max(dp[n-j], n-j)), j = 1,2, ... , n-2.

    dp = [0]*(n+1)
    dp[2] = 1
    for i in range(3, n+1):
        for j in range(1, i-1):
            dp[i] = max(dp[i], j*max(i-j, dp[i-j]))
    return dp[-1]

Log in to reply
 

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