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];
}
相关推荐
Joern-Lee13 分钟前
机器学习算法:支持向量机SVM
算法·机器学习·支持向量机
秋说23 分钟前
【PTA数据结构 | C语言版】计算1~n与1~m每一项相互乘积的和
c语言·数据结构·算法
秋说27 分钟前
【PTA数据结构 | C语言版】计算1~n平方的和加上1~n的和
c语言·数据结构·算法
C++ 老炮儿的技术栈29 分钟前
Visual Studio 2022 MFC Dialog 添加Toolbar及Tips提示
服务器·c语言·数据库·c++·ide·算法·visual studio
水果里面有苹果1 小时前
18-C#改变形参内容
java·数据结构·算法
前端拿破轮1 小时前
女朋友要和我分手?!!居然是因为交不出赎金信,不会用哈希表😭😭😭
算法·leetcode·typescript
CoovallyAIHub1 小时前
基于YOLOv11的CF-YOLO,如何突破无人机小目标检测?
深度学习·算法·计算机视觉
huihui4501 小时前
一天一道Sql题(day04)
算法
草莓熊Lotso1 小时前
【洛谷题单】--顺序结构(一)
c语言·c++·其他·刷题
lightqjx1 小时前
【数据结构】复杂度分析
c语言·开发语言·数据结构·算法