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];
}
相关推荐
CoovallyAIHub20 分钟前
搞定边缘AI部署:开源神器RamaLama,让视觉语言模型无处不在
深度学习·算法·计算机视觉
CyberSoma20 分钟前
机器人模仿学习运动基元数学编码方法还有用吗?
人工智能·算法·计算机视觉·机器人
CoovallyAIHub25 分钟前
英伟达再出「神作」!黄仁勋华盛顿GTC宣布Vera Rubin超级芯片,联手诺基亚进军6G,市值直逼5万亿美元
深度学习·算法·计算机视觉
黑菜钟1 小时前
代码随想录第50天 | 图论 基础介绍(新篇章
算法·深度优先·图论
草莓熊Lotso1 小时前
《算法闯关指南:优选算法--前缀和》--27.寻找数组的中心下标,28.除自身以外数组的乘积
开发语言·c++·算法·rpc
七夜zippoe2 小时前
仓颉语言核心特性详解:类型系统与内存安全
人工智能·算法·鸿蒙·仓颉·核心实践
星空露珠2 小时前
数独生成题目lua脚本
数据结构·数据库·算法·游戏·lua
hadage2332 小时前
--- 单源BFS权值为一算法 迷宫中离入口最近的出口 ---
算法·宽度优先
LDG_AGI2 小时前
【推荐系统】深度学习训练框架(一):深入剖析Spark集群计算中Master与Pytorch分布式计算Master的区别
人工智能·深度学习·算法·机器学习·spark
LDG_AGI2 小时前
【推荐系统】深度学习训练框架(二):深入剖析Spark Cluster模式下DDP网络配置解析
大数据·网络·人工智能·深度学习·算法·机器学习·spark