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];
}
相关推荐
重生之后端学习17 小时前
19. 删除链表的倒数第 N 个结点
java·数据结构·算法·leetcode·职场和发展
aini_lovee17 小时前
严格耦合波(RCWA)方法计算麦克斯韦方程数值解的MATLAB实现
数据结构·算法·matlab
sycmancia17 小时前
C语言学习07——变量的作用域
c语言·学习
安特尼18 小时前
推荐算法手撕集合(持续更新)
人工智能·算法·机器学习·推荐算法
鹿角片ljp18 小时前
力扣14.最长公共前缀-纵向扫描法
java·算法·leetcode
Remember_99318 小时前
【数据结构】深入理解优先级队列与堆:从原理到应用
java·数据结构·算法·spring·leetcode·maven·哈希算法
偷星星的贼1118 小时前
C++中的状态机实现
开发语言·c++·算法
程序员敲代码吗18 小时前
C++中的组合模式实战
开发语言·c++·算法
海上Bruce18 小时前
C primer plus (第六版)第十二章 编程练习第1题
c语言
52Hz11818 小时前
二叉树理论、力扣94.二叉树的中序遍历、104.二叉树的最大深度、226.反转二叉树、101.对称二叉树
python·算法·leetcode