算法设计Week18 LeetCode Algorithms Problem #344 Integer Break
2017-06-22 22:14
417 查看
题目描述:
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
= 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 ; } };
相关文章推荐
- 算法设计Week10 LeetCode Algorithms Problem #213 House Robber II
- 算法设计Week15 LeetCode Algorithms Problem #120 Triangle
- 【算法设计作业】week14
- (算法分析Week18)Subsets[Medium]
- 【算法设计作业】week17
- 算法设计Week1 LeetCode Algorithms Problem #2 Add Two Numbers
- 【算法设计作业】week16
- 算法分析与设计week11--744. Find Smallest Letter Greater Than Target
- 算法分析与设计week05--7.Reverse Integer
- (算法分析Week18)1-bit and 2-bit Characters[Easy]
- 算法设计Week16 LeetCode Algorithms Problem #322 Coin Change
- 算法分析与设计week01——1.Two Sum
- 算法分析与设计课程18——《算法概论》8.19
- 【算法设计作业】week13
- 【广告算法工程师入门 18】机制设计-关键词拍卖与机制演变
- 算法设计Week13 LeetCode Algorithms Problem #64 Minimum Path Sum
- 算法分析与设计课程(18):【leetcode】Clone Graph
- 【算法设计作业】week3
- 算法分析与设计——LeetCode Problem.12 Integer to Roman
- 算法分析与设计week09--53. Maximum Subarray