The problem from Leetcode 343, “Integer Break”, reads:
Given a positive integer n
, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
Example 1:
Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
Note:
n
is guaranteed to be greater than 1.n
include values as low as 2?
n
should be greater than 1.n
that we should consider?
n
can be reasonably large, but exact limits can usually be found in the problem constraints section of Leetcode.The problem requires breaking n
into at least two smaller positive integers such that their product is maximized. Here are the steps to tackle this:
n
, breaking it down into parts of values 1, 2, and 3 is considered optimal as 3s maximize the product in larger chunks.dp
where dp[i]
will store the maximum product obtainable for integer i
.n
and calculate the possible maximum products.i
, iterate through all j from 1 to i/2
, and calculate which combination provides the highest product using previously computed dp arrays.n
into multiple 3s. Handle the remainder cases (if n % 3 == 1
then adjust one 3 to a 4).Here is a C++ implementation using the dynamic programming approach:
#include <vector>
#include <algorithm>
#include <iostream>
int integerBreak(int n) {
if (n == 2) return 1;
if (n == 3) return 2;
std::vector<int> dp(n+1, 0);
dp[1] = 1;
dp[2] = 2;
dp[3] = 3;
int maxProduct = 0;
for (int i = 4; i <= n; ++i) {
for (int j = 1; j <= i / 2; ++j) {
dp[i] = std::max(dp[i], dp[j] * dp[i - j]);
}
}
return dp[n];
}
int main() {
int n = 10; // Example input
std::cout << "Maximum product of breaking " << n << " is: " << integerBreak(n) << std::endl;
return 0;
}
O(n^2)
n
and within that, a loop iterating up to i/2
, making it quadratic.O(n)
dp
to store the results for each integer up to n
.This approach should be efficient enough for reasonable values of n
as typically required by such Leetcode problems.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?