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

来源:互联网 发布:迪蒙小额贷款系统源码 编辑:程序博客网 时间:2024/05/29 18:31

题目描述:

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