算法设计Week18 LeetCode Algorithms Problem #344 Integer Break

题目描述:

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.


题目分析:

本题要求将一个大于2的正整数分解成至少两个正整数的和,并使分解结果的积最大。
考虑所有2-10的正整数,可以得到:
result[2]:1 * 1 = 1
result[3]:1 * 2 = 2
result[4]:2 * 2 = 4
result[5]:2 * 3 = 6
result[6]:2 * 2 * 2 = 8,而3 * 3 = 9。由此可以看到在大于6时,分出更多的3是更有利的。
result[7]:7 = 4 + 3,因此result[4] * 3 = 12
result[8]:8 = 5 + 3,因此result[5] * 3 = 18
result[9]:9 = 6 + 3,因此result[6] * 3 = 27
result[10]:10 = 7 + 3,因此result[7] * 3 = 36
由上面的列举可以看出,对于n >6的正整数,存在着状态转移方程:
result[n] = result[n - 3] * 3。


代码实现:

本题的代码实现如下所示。为了简化代码,将result[2]和result[3]分别设成2和3,就可以使n > 5的所有情况满足前面找出的状态转移方程。
算法的时间复杂度为 O(n) ,空间复杂度为 O(n)

class Solution {
public:
    int integerBreak(int n) {
        if(n == 2) return 1;
        if(n == 3) return 2;
        vector<int> result(n + 1);
        result[2] = 2;  // 为了计算方便
        result[3] = 3;  // 为了计算方便
        result[4] = 4;
        for(int i = 5; i <= n; i++){
            result[i] = result[i - 3] * 3;
        }
        return result[n];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值