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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章