Integer Break

来源:互联网 发布:明年今日 知乎 编辑:程序博客网 时间:2024/05/18 15:57

题目地址:https://leetcode.com/problems/integer-break/description/

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=1+11

3=2+12

4=2+24

5=3+26

6=3+39

7=3+2+212

8=3+3+218

9=3+3+327

10=3+3+2+236

11=3+3+3+254

好像看出点什么来了,最大积基本都是拆出来以3开头的数字,像7和10这种情况,最后剩余4的时候,一般拆成两个2,而不是拆成3和1,拆成两个2也就是4,所以就不动了。

于是代码可以这么写:

public class IntegerBreak {    public static int integerBreak(int n) {        if (n == 2)            return 1;        if (n == 3)            return 2;        int res = 1;        while (n > 4) {            res *= 3;            n -= 3;        }        return res * n;    }    public static void main(String[] args) {        for (int i = 1; i < 58; i++) {            System.out.println(i + " " + integerBreak(i));        }    }}