LeetCode解题报告 343. Integer Break [medium]
来源:互联网 发布:淘宝客服销售案例 编辑:程序博客网 时间:2024/06/05 11:32
题目描述
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.
Hint:
- There is a simple O(n) solution to this problem.
- You may check the breaking results of n ranging from 7 to 10 to discover the regularities.
解题思路
题目要求得出乘积最大的一个数的和分解。
提示中说明可以从7-10找规律。
可以看到,分解出的数字均为2或3或4,且尽量包含更多的3,不包含1.
算法很容易实现,将一个数n再减去2的值除以3的值k就是分解出来的所有的3的个数(因为1不能做因子,也就是余数不能为1,如果是n除以3或者n-1除以3,余数都有可能是1),再对余数进行分类讨论,余数为0,k个3相乘为结果;余数为2,k个3相乘再乘2;余数为3,k+1个3相乘;余数为4,k个3相乘再乘4。
这里引用http://blog.csdn.net/liyuanbhu/article/details/51198124这篇博客的证明,来解释为什么拆出足够多的
首先证明拆出的因子大于 4 是不行的。设 x 是一个因子,x>4,那么可以将这个因子再拆成两个因子 x−2 和 2,易证 (x−2)×2>x。所以不能有大于 4 的因子。4 这个因子也是可有可无的,4=2+2,4=2×2。因此 4 这个因子可以用两个 2 代替。
除非没有别的因子可用,1 也不能选作因子。一个数 x 当它大于 3 时,有 (x−2)×2>(x−1)×1。这样呢,就只剩下 2 和 3 这两个因子可以选了。下面再证明 3 比 2 好。
时间复杂度分析
O(1)的时间复杂度,无循环。
代码如下:
注意n为2或者3时,返回1/2.
class Solution {public: int integerBreak(int n) { if (n==2) { return 1; } if (n==3) { return 2; } else{ int count=(n-2)/3; int yushu=n-count*3; int result=0; if (yushu==0) { result = pow(3, count); } if (yushu==4) { result = pow(3, count)*4; } if (yushu==3) { result = pow(3, count)*3; } if (yushu==2) { result = pow(3, count)*2; } return result; } }
0 0
- LeetCode解题报告 343. Integer Break [medium]
- [leetcode] 343. Integer Break 解题报告
- leetcode 343. Integer Break 解题报告
- LeetCode 343. Integer Break 解题报告
- [Leetcode] 343. Integer Break 解题报告
- Leetcode 343. Integer Break (Medium) (cpp)
- Integer Break解题报告
- 343. Integer Break #Medium
- 343. Integer Break -Medium
- LeetCode #343 - Integer Break - Medium
- LeetCode---Integer Break解题分析
- LeetCode Word Break 解题报告
- 【LeetCode】Word Break 解题报告
- [LeetCode]Word Break,解题报告
- Word Break [Leetcode解题报告]
- (java) Integer Break解题报告
- LeetCode解题报告---Reverse Integer
- LeetCode-Reverse Integer-解题报告
- Git & GitLab 使用及规范
- java .so文件搜索路径
- 【个人Unity笔记】{基础} DOTween快捷实现震屏效果
- 单例模式-Singleton Pattern 确保对象的唯一性——单例模式 (一):单例模式的动机,单例模式概述
- ORB-SLAM2编译过程中遇到libavcodec.a问题解决
- LeetCode解题报告 343. Integer Break [medium]
- 理解Bitcode:一种中间代码
- 关于形如--error LNK2005: xxx 已经在 msvcrtd.lib ( MSVCR90D.dll ) 中定义--的问题分析解决
- Tagxedo--'词云图'使用指南
- 用户和用户组的概念
- 简单的jsp页面传值
- runtime最清晰最简单的理解
- Android 自定义View-怎么绘制居中文本?
- 【C++】【啊哈!算法】Dijkstra算法