【Leetcode】Integer Break

来源:互联网 发布:中国近10年gdp数据 编辑:程序博客网 时间:2024/06/09 07:37

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.

For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).

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

最近一直在做DP,这道题也是典型的DP。经典题型没错,看一眼就想到了,然后我列了一下前几个数字先找找规律:


1:1

2:1+1

3:1+2, 1+1+1

4:1+1+1+1,1+2+1,2+2

5: 1+1+1+1+1,1+2+1+1,2+2+1,2+3


我发现问题是,每一个数字最大组合乘积的未必是基于a和b自己最大的,而很有可能是a或b自身!所以也就是说我们的核心函数应该是

DP[x] = Max(dp[x], max(i,dp[i])*max(i-j,dp[i-j]))

于是code长成了这样:

public class Solution {    public int integerBreak(int n) {        int[] res = new int[n+1];        res[1]=1;        for(int i=2;i<n+1;i++){            for(int j=1;j*2<=i;j++){                res[i] = Math.max(res[i], (Math.max(j,res[j])) * (Math.max(i - j, res[i - j])));            }        }        return res[n];    }}
其中第二个for loop为了更快,只需要找一半就行了,反正都是对称的。

0 0
原创粉丝点击