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];
}
相关推荐
坚持编程的菜鸟6 小时前
模拟实现memmove
c语言·算法·模拟实现memmove
wabs6667 小时前
关于图论【最短路径之Dijkstra算法(堆优化版)|卡码网47.参加科学大会的思考】
数据结构·算法·图论·优先级队列·邻接表·小顶堆·卡码网
坚持编程的菜鸟7 小时前
编写判断大小端程序
c语言·算法·判断大小端
papaofdoudou7 小时前
判断排列逆序奇偶性的乘积判别法(范德蒙德符号法)
人工智能·算法
linux-hzh8 小时前
百日算法修炼 · Day 03
java·算法
问商十三载8 小时前
RAG 检索效果差怎么排查?2026 五层诊断法完整指南
开发语言·人工智能·windows·python·算法
不负岁月无痕8 小时前
简单理解操作系统结构
java·linux·c语言·开发语言·c++·面试
qq_448011169 小时前
C语言中的指针函数和函数指针
java·c语言·开发语言
嵌入式老牛9 小时前
三相电气量采集模块设计(三)非同步采样时的精度提升
算法·精度·计量
clerly10 小时前
C语言如何实现继承?
c语言·多态·继承·封装·结构体