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];
}
相关推荐
学嵌入式的小杨同学5 分钟前
循环队列(顺序存储)完整解析与实现(数据结构专栏版)
c语言·开发语言·数据结构·c++·算法
程序员-King.5 分钟前
day128—二分查找—搜索二维矩阵(LeetCode-74)
leetcode·矩阵·二分查找
shangjian0076 分钟前
AI大模型-机器学习-算法-线性回归-优化方法
人工智能·算法·机器学习
shangjian00710 分钟前
AI大模型-机器学习-算法-逻辑回归
人工智能·算法·机器学习
王锋(oxwangfeng)11 分钟前
车道线拟合算法--自动驾驶
人工智能·算法·自动驾驶
computersciencer12 分钟前
一文快速理解线性回归的过程
算法·机器学习·回归·线性回归
VT.馒头17 分钟前
【力扣】2627. 函数防抖
前端·javascript·算法·leetcode
凌~风17 分钟前
014-计算机操作系统实验报告之C 程序的编写!
c语言·开发语言·实验报告
想逃离铁厂的老铁17 分钟前
Day41 >> 121、买卖股票的最佳时机 + 122.买卖股票的最佳时机II + 123.买卖股票的最佳时机III
算法·leetcode
夏鹏今天学习了吗18 分钟前
【LeetCode热题100(79/100)】打家劫舍
算法·leetcode·职场和发展