343. Integer Break (划分整数使乘积最大)

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:

  1. There is a simple O(n) solution to this problem.
  2. You may check the breaking results of n ranging from 7 to 10 to discover the regularities.

题目大意:给定一个正整数n,将n划分为至少两个数,找到一种方案,使得这些数相加的和等于n,并且这些数的乘积达到最大。(默认n的取值范围为[2,58])

解题思路:

当n=2时,只能划分为1*1;

当n=3时,只能划分为2*1;

当 n=4 时,可以划分为2*2(或者不划分也是一样的);

当n>=5时,3*(n-3) >= 2*(n-2) > n,所以划分为3*(n-3),再对(n-3)继续进行划分。

代码如下:(0ms,beats 50.31%)

public class Solution {
    public int integerBreak(int n) {
        if (n <= 3)
			return n - 1;
		int product = 1;
		while (n > 4) {
			product *= 3;
			n -= 3;
		}
		product *= n;
		return product;
    }
}
    原文作者:大整数乘法问题
    原文地址: https://blog.csdn.net/xiangwanpeng/article/details/53326761
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞