修改了121.买卖股票的最佳时机的java题解

This commit is contained in:
LiHua
2021-11-23 18:33:52 +08:00
parent e85fbba56a
commit 7cef253757

View File

@ -195,23 +195,26 @@ public:
## 其他语言版本
Java
> 贪心法:
```java
// 贪心思路
class Solution {
public int maxProfit(int[] prices) {
int minprice = Integer.MAX_VALUE;
int maxprofit = 0;
for (int i = 0; i < prices.length; i++) {
if (prices[i] < minprice) {
minprice = prices[i];
} else if (prices[i] - minprice > maxprofit) {
maxprofit = prices[i] - minprice;
}
// 找到一个最小的购入点
int low = Integer.MAX_VALUE;
// res不断更新直到数组循环完毕
int res = 0;
for(int i = 0; i < prices.length; i++){
low = Math.min(prices[i], low);
res = Math.max(prices[i] - low, res);
}
return maxprofit;
return res;
}
}
```
> 动态规划:版本一
```java
// 解法1
class Solution {
@ -233,30 +236,27 @@ class Solution {
}
```
> 动态规划:版本二
``` java
class Solution { // 动态规划解法
public int maxProfit(int[] prices) {
// 可交易次数
int k = 1;
// [天数][交易次数][是否持有股票]
int[][][] dp = new int[prices.length][k + 1][2];
// bad case
dp[0][0][0] = 0;
dp[0][0][1] = Integer.MIN_VALUE;
dp[0][1][0] = Integer.MIN_VALUE;
dp[0][1][1] = -prices[0];
for (int i = 1; i < prices.length; i++) {
for (int j = k; j >= 1; j--) {
// dp公式
dp[i][j][0] = Math.max(dp[i - 1][j][0], dp[i - 1][j][1] + prices[i]);
dp[i][j][1] = Math.max(dp[i - 1][j][1], dp[i - 1][j - 1][0] - prices[i]);
}
}
return dp[prices.length - 1][k][0] > 0 ? dp[prices.length - 1][k][0] : 0;
class Solution {
public int maxProfit(int[] prices) {
int[] dp = new int[2];
dp[0] = -prices[0];
dp[1] = 0;
// 可以参考斐波那契问题的优化方式
// dp[0] 和 dp[1], 其实是第 0 天的数据
// 所以我们从 i=1 开始遍历数组,一共有 prices.length 天,
// 所以是 i<=prices.length
for (int i = 1; i <= prices.length; i++) {
int temp = dp[0];
// 前一天持有;或当天买入
dp[0] = Math.max(temp, -prices[i - 1]);
// 前一天卖出;或当天卖出, 当天要卖出,得前一天持有才行
dp[1] = Math.max(dp[1], temp + prices[i - 1]);
}
return dp[1];
}
}
```