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];
      }
    
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值