0%

LeetCode-714

题目

Snipaste_2020-12-17_09-17-21.png

结果

Snipaste_2020-12-17_09-17-32.png

代码

DP之二维数组

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int maxProfit(int[] prices, int fee) {
int[][] dp = new int[prices.length][2];
dp[0][0] = 0;
dp[0][1] = -prices[0];
for (int i = 1; i < dp.length; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i] - fee);
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
}
return dp[dp.length - 1][0];
}
}

DP之一位数组×2

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int maxProfit(int[] prices, int fee) {
int[] dp1 = new int[prices.length];
int[] dp2 = new int[prices.length];
dp2[0] = -prices[0];
for (int i = 1; i < prices.length; i++) {
dp1[i] = Math.max(dp1[i - 1], dp2[i - 1] + prices[i] - fee);
dp2[i] = Math.max(dp2[i - 1], dp1[i - 1] - prices[i]);
}
return dp1[prices.length - 1];
}
}

DP之再优化

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int maxProfit(int[] prices, int fee) {
int a = 0;
int b = -prices[0];
for (int i = 1; i < prices.length; i++) {
a = Math.max(a, b + prices[i] - fee);
b = Math.max(b, a - prices[i]);
}
return a;
}
}

复杂度

时间复杂度:O(n)

空间复杂度:O(1)