【LeetCode】343. Integer Break 整数拆分(Medium)(JAVA)

【LeetCode】343. Integer Break 整数拆分(Medium)(JAVA)

题目地址: https://leetcode.com/problems/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.

Example 1:

Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.

Example 2:

Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.

Note: You may assume that n is not less than 2 and not larger than 58.

题目大意

给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。

说明: 你可以假设 n 不小于 2 且不大于 58。

解题方法

  1. 采用动态规划,用 dp[i] 表示 i 的最大取值
  2. 要计算 dp[i], 首先 dp[i] 之前的所有值都是已知的。那就从 [1, i - 1] 一个乘起来,计算最大值,乘的时候,要取 k 和 dp[k] 的最大值
class Solution {
    public int integerBreak(int n) {
        int[] dp = new int[n + 1];
        dp[1] = 1;
        for (int i = 2; i <= n; i++) {
            int max = i / 2;
            for (int j = 1; j <= max; j++) {
                dp[i] = Math.max(dp[i], Math.max(j, dp[j]) * Math.max(i - j, dp[i - j]));
            }
        }
        return dp[n];
    }
}

执行耗时:1 ms,击败了61.61% 的Java用户
内存消耗:35.3 MB,击败了62.92% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值