第十六周LeetCode

题目
Integer Break
难度 Medium

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.

实现思路

可以用动态规划实现。用max_i[i]表示和为数字i的最大的乘积,那么max_[i]取决于和为i的组合j,i-j,max_i[j]和max_i[i-j],max_i[i]应为max_i[j]和j的最大值和max_i[i-j],j的最大值的乘积,即
max_i[i]=max(max_i[j],j)*max(max_i[i-j],j)。

实现代码

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

        return max_i[n];
    }
};

猜你喜欢

转载自blog.csdn.net/unirrrrr/article/details/78858883