LeetCode //C - 343. Integer Break

343. Integer Break

Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers.

Return the maximum product you can get.

Example 1:

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

Example 2:

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

Constraints:
  • 2 <= n <= 58

From: LeetCode

Link: 343. Integer Break


Solution:

Ideas:

1. Initialization:

  • Create a dp array where dp[i] represents the maximum product obtainable by breaking the integer i.

2. Dynamic Programming Fill:

  • For each integer i from 2 to n, compute the maximum product by trying every possible break of i into two parts j and i - j.
  • Update dp[i] with the maximum of the current value, j * (i - j), and j * dp[i - j].

3. Result:

  • The result for the integer n is stored in dp[n].
Code:
c 复制代码
int integerBreak(int n) {
    // Base case for n = 2
    if (n == 2) return 1;
    
    // Create an array to store the maximum product for each number up to n
    int dp[n + 1];
    
    // Initialize the dp array with zeroes
    for (int i = 0; i <= n; i++) {
        dp[i] = 0;
    }
    
    // Fill the dp array with the maximum products
    for (int i = 2; i <= n; i++) {
        for (int j = 1; j < i; j++) {
            // Calculate the maximum product by either breaking or not breaking the number
            dp[i] = (dp[i] > j * (i - j)) ? dp[i] : j * (i - j);
            dp[i] = (dp[i] > j * dp[i - j]) ? dp[i] : j * dp[i - j];
        }
    }
    
    return dp[n];
}
相关推荐
2501_941803624 分钟前
在柏林智能城市照明场景中构建实时调控与高并发能耗数据分析平台的工程设计实践经验分享
算法
福楠9 分钟前
C++ STL | list
c语言·开发语言·数据结构·c++·算法·list
努力学算法的蒟蒻10 分钟前
day55(1.6)——leetcode面试经典150
算法·leetcode·面试
s砚山s10 分钟前
代码随想录刷题——二叉树篇(十)
算法
2301_7644413312 分钟前
基于HVNS算法和分类装载策略的仓储系统仿真平台
人工智能·算法·分类
AI科技星16 分钟前
统一场论变化的引力场产生电磁场推导与物理诠释
服务器·人工智能·科技·线性代数·算法·重构·生活
myloveasuka17 分钟前
int类型的取值范围(为什么负数比正数表示的范围多一位)
c语言·c++
杰克逊的日记18 分钟前
规控算法(规划 + 控制算法)
大数据·算法·云计算·it
玉树临风ives18 分钟前
atcoder ABC439 题解
c++·算法
程序员zgh22 分钟前
类AI技巧 —— 文字描述+draw.io 自动生成图表
c语言·c++·ai作画·流程图·ai编程·甘特图·draw.io