Skip to content

Commit 0f184d9

Browse files
committed
DP
分割整数以及 股票交易两类题型 日不会做
1 parent b50bfdd commit 0f184d9

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package DP.其他问题如股票;
2+
3+
/**
4+
* Created by 周杰伦 on 2018/4/9.
5+
*/
6+
public class 买入和售出股票最大的收益 {
7+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package DP.分割整数;
2+
3+
/**
4+
* Created by 周杰伦 on 2018/4/9.
5+
*/
6+
public class 分割整数的最大乘积自写 {
7+
// 2 = 1+1 3 = 1+2 4=2+2 5=2+3 6=3+3
8+
public static void main(String[] args) {
9+
System.out.println(integerBreak(10));
10+
}
11+
public static int integerBreak(int n) {
12+
if (n == 1 || n == 0)return 0;
13+
int []dp = new int[n + 1];
14+
dp[0] = 0;
15+
dp[1] = 1;
16+
dp[2] = 1;
17+
for (int i = 3;i <= n;i ++) {
18+
for (int j = 1;j < i;j ++ ) {
19+
dp[i] = Math.max(dp[i],dp[j] * (i - j));
20+
if ((i-j) * j > dp[i] ) dp[i] = (i - j) * j;
21+
}
22+
}
23+
return dp[n];
24+
}
25+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package DP.分割整数;
2+
3+
/**
4+
* Created by 周杰伦 on 2018/4/9.
5+
*/
6+
public class 按平方数来分割整数自写 {
7+
public static void main(String[] args) {
8+
System.out.println(numSquares(12));
9+
}
10+
public static int numSquares(int n) {
11+
int []dp = new int[n + 1];
12+
dp[1] = 1;
13+
for (int i = 2;i <= n;i ++) {
14+
//默认等于前一位+1
15+
dp[i] = dp[i - 1] + 1;
16+
if (isSquare(i)) {
17+
dp[i] = 1;
18+
continue;
19+
}
20+
//当差为平方数时直接 等于其+1即可。这样的时间复杂度大大降低。
21+
//为onlogn.否则是on2不符合要求
22+
for (int j = 1;j * j < i;j ++) {
23+
dp[i] = Math.min(dp[i], dp[i - j * j] + 1);
24+
}
25+
}
26+
return dp[n];
27+
}
28+
public static boolean isSquare(int n) {
29+
if (Math.ceil(Math.pow(n,0.5)) == Math.pow(n,0.5)) {
30+
return true;
31+
}
32+
return false;
33+
}
34+
}

0 commit comments

Comments
 (0)