LeetCode 343. Integer Break

Posted 浩然

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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:

  1. There is a simple O(n) solution to this problem.
  2. You may check the breaking results of n ranging from 7 to 10 to discover the regularities.

数学题。

 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 }
View Code

也可以用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

 

以上是关于LeetCode 343. Integer Break的主要内容,如果未能解决你的问题,请参考以下文章

leetcode [343]Integer Break

[leetcode] 343. Integer Break

leetcode@ [343] Integer Break (Math & Dynamic Programming)

343 Integer Break 整数拆分

LeetCode 343. 整数拆分 | Python

*leetcode 343. 整数拆分 & 剑指offer 14