算法设计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的所有情况满足前面找出的状态转移方程。
算法的时间复杂度为
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]; }};
- 算法设计Week18 LeetCode Algorithms Problem #344 Integer Break
- [LeetCode]problem 343. Integer Break
- 算法设计Week1 LeetCode Algorithms Problem #1 Two Sum
- 算法设计Week1 LeetCode Algorithms Problem #2 Add Two Numbers
- 算法设计Week3 LeetCode Algorithms Problem #133 Clone Graph
- 算法设计Week4 LeetCode Algorithms Problem #207 Course Schedule
- 算法设计Week6 LeetCode Algorithms Problem #455 Assign Cookies
- 算法设计Week7 LeetCode Algorithms Problem #53 Maximum Subarray
- 算法设计Week8 LeetCode Algorithms Problem #70 Climbing Stairs
- 算法设计Week8 LeetCode Algorithms Problem #198 House Robber
- 算法设计Week10 LeetCode Algorithms Problem #213 House Robber II
- 算法设计Week11 LeetCode Algorithms Problem #303 Range Sum Query
- 算法设计Week12 LeetCode Algorithms Problem #62 Unique Paths
- 算法设计Week12 LeetCode Algorithms Problem #63 Unique Paths II
- 算法设计Week13 LeetCode Algorithms Problem #64 Minimum Path Sum
- 算法设计Week14 LeetCode Algorithms Problem #91 Decode Ways
- 算法设计Week15 LeetCode Algorithms Problem #120 Triangle
- 算法设计Week16 LeetCode Algorithms Problem #322 Coin Change
- LeetCode20——Valid Parentheses(括号匹配问题,使用栈的知识)
- Java for Web学习笔记(六六):Service和Repository(1)抽象分层
- 微信公众平台开发之模板消息(Java)
- Java的动态绑定和静态绑定的理解
- 输入一个链表,从尾到头打印链表每个节点的值。
- 算法设计Week18 LeetCode Algorithms Problem #344 Integer Break
- 数据通信基础
- UVA 12627 Erratic Expansion (递归,分治)
- http://blog.csdn.net/znyyjk/article/details/52717336
- css资源收集
- java中的反射
- 正则表达式
- leetcode209. Minimum Size Subarray Sum
- 【用Python学习Caffe】4. 设计自己的网络结构