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];
}
相关推荐
源代码•宸6 分钟前
Golang原理剖析(彻底理解Go语言栈内存/堆内存、Go内存管理)
经验分享·后端·算法·面试·golang·span·mheap
黎子越8 分钟前
python循环相关联系
开发语言·python·算法
myloveasuka9 分钟前
汉明编码的最小距离、汉明距离
服务器·数据库·笔记·算法·计算机组成原理
沛沛rh459 分钟前
Rust浮点数完全指南:从基础到实战避坑
深度学习·算法·计算机视觉·rust
近津薪荼19 分钟前
优选算法——双指针1(数组分块)
c++·学习·算法
Дерек的学习记录20 分钟前
二叉树(下)
c语言·开发语言·数据结构·学习·算法·链表
单片机系统设计25 分钟前
基于STM32的宠物智能喂食系统
c语言·stm32·单片机·嵌入式硬件·物联网·毕业设计·宠物
leaves falling28 分钟前
c语言- 有序序列合并
c语言·开发语言·数据结构
代码无bug抓狂人36 分钟前
前缀和算法和单调队列算法(经典例题)
数据结构·算法
We་ct37 分钟前
LeetCode 14. 最长公共前缀:两种解法+优化思路全解析
前端·算法·leetcode·typescript