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];
}
相关推荐
初夏睡觉2 分钟前
P1055 [NOIP 2008 普及组] ISBN 号码
算法·p1055
程芯带你刷C语言简单算法题6 分钟前
Day28~实现strlen、strcpy、strncpy、strcat、strncat
c语言·c++·算法·c
踏浪无痕18 分钟前
周末拆解:QLExpress 如何做到不编译就能执行?
后端·算法·架构
一个不知名程序员www20 分钟前
算法学习入门--- 树(C++)
c++·算法
如竟没有火炬31 分钟前
四数相加贰——哈希表
数据结构·python·算法·leetcode·散列表
背心2块钱包邮1 小时前
第9节——部分分式积分(Partial Fraction Decomposition)
人工智能·python·算法·机器学习·matplotlib
仰泳的熊猫1 小时前
1148 Werewolf - Simple Version
数据结构·c++·算法·pat考试
chao1898441 小时前
MATLAB中的多重网格算法与计算流体动力学
开发语言·算法·matlab
大工mike1 小时前
代码随想录算法训练营第四十四天 | 99.岛屿数量 深搜 99.岛屿数量 广搜 100. 岛屿的最大面积
算法
不穿格子的程序员1 小时前
从零开始学算法——链表篇3:合并两个有序链表 + 两数相加
数据结构·算法·链表·dummy