(DP 暂时不会) leetcode 343. Integer Break

mac2022-06-30  56

Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.

Example 1:

Input: 2 Output: 1 Explanation: 2 = 1 + 1, 1 × 1 = 1.

Example 2:

Input: 10 Output: 36 Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.

Note: You may assume that n is not less than 2 and not larger than 58.

===============================================

这个可以用DP,时间复杂度是O(n^2)。

dp[i] = max(i],max(j,dp[j])*max(i-j,dp[i-j]));  这个状态转移式中,我认为,j + (i - j) = i,所以,能够表示可能的最大乘积为 i * ( i- j),不过可以用到之前的dp[j]和dp[i-j],因为,其中dp[j]可以是j的最大的分解结果,也可以是i的最大的分解结果。

C++代码:

class Solution { public: int integerBreak(int n) { vector<int> dp(n+1,0); dp[1] = dp[2] = 1; for(int i = 3; i <= n; i++){ for(int j = 1; j <= i; j++){ dp[i] = max(dp[i],max(j,dp[j])*max(i-j,dp[i-j])); } } return dp[n]; } };

 

转载于:https://www.cnblogs.com/Weixu-Liu/p/10864839.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)