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 dpi 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 dpi with the maximum of the current value, j * (i - j), and j * dpi - j.

3. Result:

  • The result for the integer n is stored in dpn.
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];
}
相关推荐
怕浪猫4 小时前
RAG 面试 6 连问,从原理到优化全部覆盖
python·算法·面试
yyy(十一月限定版)4 小时前
224redfg
c语言
无线通信科研笔记4 小时前
IEEE TVT 2026 论文精读与完整复现|相位误差如何重塑近场 RIS 的幅相响应
论文阅读·人工智能·python·算法·论文笔记
mmmmath_35 小时前
二叉树の递归遍历
算法
All for pursuit.6 小时前
【位运算-1】338.比特位计数
数据结构·c++·算法·leetcode
小师兄吃牛肉6 小时前
C语言中的nullptr有必要吗
c语言·c++·算法
lhbweilai8 小时前
深挖FreeRTOS内核实现(三)
c语言·stm32·单片机
一只小小的芙厨8 小时前
【线性DP】
学习·算法·动态规划
xxwl5858 小时前
数据结构知识点和代码实现总结(C语言实现)
c语言·开发语言·数据结构
奋发向前wcx8 小时前
CSP-J复赛模拟赛5 王晨旭补题 2026.10.5
算法