forked from geekxh/hello-algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
57 lines (52 loc) · 1.26 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
* @author Anonymous
* @since 2019/11/20
*/
public class Solution {
/**
* 剪绳子求最大乘积(动态规划)
*
* @param length 绳子长度
* @return 乘积最大值
*/
public int maxProductAfterCutting1(int length) {
if (length < 2) {
return 0;
}
if (length < 4) {
return length - 1;
}
int[] res = new int[length + 1];
res[1] = 1;
res[2] = 2;
res[3] = 3;
for (int i = 4; i <= length; ++i) {
int max = 0;
for (int j = 1; j <= i / 2; ++j) {
max = Math.max(max, res[j] * res[i - j]);
}
res[i] = max;
}
return res[length];
}
/**
* 剪绳子求最大乘积(贪心算法)
*
* @param length 绳子长度
* @return 乘积最大值
*/
public int maxProductAfterCutting2(int length) {
if (length < 2) {
return 0;
}
if (length < 4) {
return length - 1;
}
int timesOf3 = length / 3;
if (length % 3 == 1) {
--timesOf3;
}
int timesOf2 = (length - timesOf3 * 3) >> 1;
return (int) (Math.pow(3, timesOf3) * Math.pow(2, timesOf2));
}
}