LeetCode 343. Integer Break
https://leetcode.com/problems/integer-break/
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.
For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).
Note: you may assume that n is not less than 2.
Hint:
- There is a simple O(n) solution to this problem.
- You may check the breaking results of n ranging from 7 to 10 to discover the regularities.
数学题。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 using namespace std; 3 4 class Solution { 5 public: 6 int integerBreak(int n) { 7 if (n == 2) return 1; 8 if (n == 3) return 2; 9 10 int product = 1; 11 while (n > 4) 12 { 13 n -= 3; 14 product *= 3; 15 } 16 product *= n; 17 18 return product; 19 } 20 }; 21 22 int main () 23 { 24 Solution testSolution; 25 int result; 26 27 result = testSolution.integerBreak(5); 28 cout << result << endl; 29 30 char ch; 31 cin >> ch; 32 33 return 0; 34 }
也可以用DP,但自己写的DP想错了,想到分解成MAX(N-2 * 2, N-3 * 3), 应该用MAX(MAX, I-J * J)。
https://leetcode.com/discuss/102024/java-greedy-o-logn-simple-code-and-o-n-2-dp