LeetCode 343 Integer Break

LeetCode 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:
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.

Amazing numeric question?。。】吹胔int試了一下才發(fā)現(xiàn),把數(shù)字分解成n個3再加3,4,5的形式,能夠讓product最大。注意當(dāng)n>=5時才滿足這個規(guī)律。

public class Solution {
    public int integerBreak(int n) {
        if (n <= 2) return 1;
        if (n == 3) return 2;
        if (n == 4) return 4;
        if (n == 5) return 6;
        if (n == 6) return 9;
        
        int div = n / 3;
        int modular = n % 3;
        if (modular == 0) {
            return (int)Math.pow(3,div);
        } else if (modular == 1) {
            return (int)Math.pow(3,div - 1) * (3 + modular);
        } else {
            return (int)Math.pow(3,div) * modular;
        }
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,921評論 0 33
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,089評論 0 23
  • 信念,只要有一點點差別,一切都會不同了。 以前沒有考慮過信念的問題,一直都是憑著自己的直覺在處事、辦事。 這件事情...
    奮斗的小雀雀閱讀 821評論 1 0
  • 一朵白云掛在天上 雪白雪白的一團(tuán)輕飄的定格在空中 我著了迷沒注意路上的坑摔倒在地 膝蓋滲出了血走得一瘸一拐 等我想...
    陳小煩_閱讀 314評論 8 0
  • 春望 文/燕趙北羽 寒風(fēng)吹未盡,酥雨潤新春。亭榭聽笛客,斷是望鄉(xiāng)人。遠(yuǎn)山眉含黛,近水柳綻新。云高江海闊,天地寄游魂。
    燕趙北羽閱讀 446評論 2 5

友情鏈接更多精彩內(nèi)容