leetcode 343. Integer Break ->可以证明,拆成的3越多,最后的乘积越大

来源:互联网 发布:stm8单片机gpio引脚 编辑:程序博客网 时间:2024/05/16 12:58

343. Integer Break

 
 My Submissions
  • Total Accepted: 21257
  • Total Submissions: 49611
  • Difficulty: Medium

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).

//直接计算可以拆成多少个3,并对余数做特殊处理:

public class Solution {    public int integerBreak(int n) {        if(n==2)return 1;        if(n==3)return 2;        int num=n/3;        int y = n%3;        if(y==1)num--;        int product=1;        for(int i=1;i<=num;i++){            product*=3;        }        if(y==1)product *= 4;        if(y==2) product*=2;        return product;            }}

牛人递归4行解法:

public int integerBreak(int n) {    if(n==2) return 1;    if(n==3) return 2;    if(n==4) return 4;    return 3 * (Math.max(n-3,integerBreak(n-3)));}


0 0