343. Integer Break

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.

  • 題目大意:給定一個正整數n,分解爲至少兩個以上的數相加使得其和爲n,找出所有分解中的最大的積。

  • 思路:n = 2 max = 1(1 + 1)

    n = 3 max = 2(1 + 2)

    n = 4 max = 4(2 + 2)

    n = 5 max = 6(2 + 3)

    n = 6 max = 9(3 + 3)

    n = 7 max = 12(3 + 2 + 2)

    n = 8 max = 16(2 + 2 + 2 + 2)

    n = 9 max = 27(3 + 3 + 3)

    n = 10 max = 36(2 + 2 + 3 + 3)

    大致也發現了一點規律,我們都分解爲1 2 3這樣的組合。

    很簡單,如果組合爲4,4又可以分解爲2 + 2,如果組合爲5,5又可以分解爲2 + 3。

  • 代碼1:

    public static int integerBreak(int n) {
          if (n <= 3) {
              return n - 1;
          }
          int[] dp = new int[n+1];
          dp[1] = 1;
          dp[2] = 2;
          dp[3] = 3;
          for(int i=4;i<=n;i++) {
              dp[i] = Math.max(2 * dp[i - 2],3 * dp[i - 3]);
          }
          return dp[n];
      }
  • 代碼2:

    package DP;
    
    /**
    * @author OovEver
    * 2018/1/4 22:32
    */
    public class LeetCode343 {
      public static int integerBreak(int n) {
          int[] dp = new int[n + 1];
          dp[1] = 1;
          for(int i=2;i<=n;i++) {
              for(int j=1;j<i;j++) {
                  dp[i] = Math.max(dp[i], Math.max(j, dp[j]) * Math.max(i - j, dp[i - j]));
              }
          }
          return dp[n];
      }
    
    }
    
發佈了207 篇原創文章 · 獲贊 69 · 訪問量 39萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章