Skip to content

Commit a2172e7

Browse files
committed
Add solution 0343 [Java]
Integer break
1 parent 21594fe commit a2172e7

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ Complete [solutions](https://github.com/doocs/leetcode/tree/master/solution) to
9999
| 0180 | [Consecutive Numbers](https://github.com/doocs/leetcode/tree/master/solution/0180.Consecutive%20Numbers) | `SQL` |
100100
| 0184 | [Department Highest Salary](https://github.com/doocs/leetcode/tree/master/solution/0184.Department%20Highest%20Salary) | `SQL` |
101101
| 0328 | [Odd Even Linked List](https://github.com/doocs/leetcode/tree/master/solution/0328.Odd%20Even%20Linked%20List) | `Linked List` |
102+
| 0343 | [Integer Break](https://github.com/doocs/leetcode/tree/master/solution/0343.Integer%20Break) | `Math`, `Dynamic Programming` |
102103

103104

104105
### Hard

solution/0343.Integer Break/README.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
## 整数拆分
2+
### 题目描述
3+
4+
给定一个正整数 n,将其拆分为**至少**两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。
5+
6+
**示例 1:**
7+
```
8+
输入: 2
9+
输出: 1
10+
解释: 2 = 1 + 1, 1 × 1 = 1。
11+
```
12+
13+
**示例 2:**
14+
```
15+
输入: 10
16+
输出: 36
17+
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。
18+
```
19+
20+
**说明:** 你可以假设 n 不小于 2 且不大于 58。
21+
22+
### 解法
23+
本题利用贪心法求解。
24+
25+
当 n>=5 时,尽可能多地拆分为 3。当剩下的正数为 4 时,把正数拆分为两个 2。
26+
27+
**证明:**
28+
29+
首先,当 n>=5 时,可以证明 2(n-2)>n,并且 3(n-3)>n。也就是说,数字大于等于 5 时,把它拆分为数字 3 或者 2。
30+
31+
另外,当 n>=5 时,3(n-3)>=2(n-2)。因此,尽可能多地拆分为整数 3。
32+
33+
当 n=4 时,其实没必要拆分,只是题目要求至少要拆分为两个整数。那么就拆分为两个 2。
34+
35+
```java
36+
class Solution {
37+
public int integerBreak(int n) {
38+
if (n < 2) {
39+
return 0;
40+
}
41+
if (n < 4) {
42+
return n - 1;
43+
}
44+
45+
int timesOf3 = n / 3;
46+
if (n % 3 == 1) {
47+
--timesOf3;
48+
}
49+
int timesOf2 = (n - timesOf3 * 3) >> 1;
50+
return (int) (Math.pow(2, timesOf2) * Math.pow(3, timesOf3));
51+
}
52+
}
53+
```
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
public int integerBreak(int n) {
3+
if (n < 2) {
4+
return 0;
5+
}
6+
if (n < 4) {
7+
return n - 1;
8+
}
9+
10+
int timesOf3 = n / 3;
11+
if (n % 3 == 1) {
12+
--timesOf3;
13+
}
14+
int timesOf2 = (n - timesOf3 * 3) >> 1;
15+
return (int) (Math.pow(2, timesOf2) * Math.pow(3, timesOf3));
16+
}
17+
}

0 commit comments

Comments
 (0)