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:
题目要求得出乘积最大的一个数的和分解。
提示中说明可以从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。
这里引用,来解释为什么拆出足够多的 3 就能使得乘积最大。
首先证明拆出的因子大于 4 是不行的。设 x 是一个因子,x>4,那么可以将这个因子再拆成两个因子 x−2 和 2,易证 (x−2)×2>x。所以不能有大于 4 的因子。4 这个因子也是可有可无的,4=2+2,4=2×2。因此 4 这个因子可以用两个 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;}}
本文发布于:2024-02-03 00:03:54,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170688983447338.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |