Skip to content

Commit 7cef253

Browse files
committed
修改了121.买卖股票的最佳时机的java题解
1 parent e85fbba commit 7cef253

File tree

1 file changed

+32
-32
lines changed

1 file changed

+32
-32
lines changed

problems/0121.买卖股票的最佳时机.md

Lines changed: 32 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -195,23 +195,26 @@ public:
195195
## 其他语言版本
196196

197197
Java:
198+
199+
> 贪心法:
200+
198201
```java
199-
// 贪心思路
200202
class Solution {
201203
public int maxProfit(int[] prices) {
202-
int minprice = Integer.MAX_VALUE;
203-
int maxprofit = 0;
204-
for (int i = 0; i < prices.length; i++) {
205-
if (prices[i] < minprice) {
206-
minprice = prices[i];
207-
} else if (prices[i] - minprice > maxprofit) {
208-
maxprofit = prices[i] - minprice;
209-
}
204+
// 找到一个最小的购入点
205+
int low = Integer.MAX_VALUE;
206+
// res不断更新,直到数组循环完毕
207+
int res = 0;
208+
for(int i = 0; i < prices.length; i++){
209+
low = Math.min(prices[i], low);
210+
res = Math.max(prices[i] - low, res);
210211
}
211-
return maxprofit;
212+
return res;
212213
}
213214
}
214215
```
216+
> 动态规划:版本一
217+
215218
```java
216219
// 解法1
217220
class Solution {
@@ -233,30 +236,27 @@ class Solution {
233236
}
234237
```
235238

236-
``` java
237-
class Solution { // 动态规划解法
238-
public int maxProfit(int[] prices) {
239-
// 可交易次数
240-
int k = 1;
241-
// [天数][交易次数][是否持有股票]
242-
int[][][] dp = new int[prices.length][k + 1][2];
243-
244-
// bad case
245-
dp[0][0][0] = 0;
246-
dp[0][0][1] = Integer.MIN_VALUE;
247-
dp[0][1][0] = Integer.MIN_VALUE;
248-
dp[0][1][1] = -prices[0];
249-
250-
for (int i = 1; i < prices.length; i++) {
251-
for (int j = k; j >= 1; j--) {
252-
// dp公式
253-
dp[i][j][0] = Math.max(dp[i - 1][j][0], dp[i - 1][j][1] + prices[i]);
254-
dp[i][j][1] = Math.max(dp[i - 1][j][1], dp[i - 1][j - 1][0] - prices[i]);
255-
}
256-
}
239+
> 动态规划:版本二
257240

258-
return dp[prices.length - 1][k][0] > 0 ? dp[prices.length - 1][k][0] : 0;
241+
``` java
242+
class Solution {
243+
public int maxProfit(int[] prices) {
244+
int[] dp = new int[2];
245+
dp[0] = -prices[0];
246+
dp[1] = 0;
247+
// 可以参考斐波那契问题的优化方式
248+
// dp[0] 和 dp[1], 其实是第 0 天的数据
249+
// 所以我们从 i=1 开始遍历数组,一共有 prices.length 天,
250+
// 所以是 i<=prices.length
251+
for (int i = 1; i <= prices.length; i++) {
252+
int temp = dp[0];
253+
// 前一天持有;或当天买入
254+
dp[0] = Math.max(temp, -prices[i - 1]);
255+
// 前一天卖出;或当天卖出, 当天要卖出,得前一天持有才行
256+
dp[1] = Math.max(dp[1], temp + prices[i - 1]);
259257
}
258+
return dp[1];
259+
}
260260
}
261261
```
262262

0 commit comments

Comments
 (0)