343. Integer Break整数拆分

Integer Break

题目描述

leetcode.343

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.

给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。

示例 1:

输入: 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1。
示例 2:

输入: 10
输出: 36
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。
说明: 你可以假设 n 不小于 2 且不大于 58。

解题

这道题直观上就感觉和0-1背包问题很像,不过这里不是拿不拿的问题,而是要有记忆搜索,当前的值跟之前的有关,通过记录之前的值,得到当前最优解。
依旧老套路,当前最大值,一种情况是等于从前往到此处遍历,例如,当前为10,从前到这,当j=1时,还剩9,则当前最大值必然等于1乘和为9的最大乘积,而由于此题是二分及以上分法,上一个情况那个和为9必然是二分,再加上这个1的情况最低划分是三分这个和,因此还要比较一个二分的情况。
动态转移方程为:
d p [ i ] = m a x ( d p [ i ] , m a x ( j d p [ i j ] , ( i j ) j ) ) dp[i]=max(dp[i],max(j*dp[i-j],(i-j)*j))

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

猜你喜欢

转载自blog.csdn.net/weixin_43554642/article/details/88256300