Skip to content

Commit

Permalink
统一了123优化空间写法的java解题代码格式
Browse files Browse the repository at this point in the history
  • Loading branch information
spacker-343 committed Nov 24, 2021
1 parent eacf15d commit 5fc3536
Showing 1 changed file with 24 additions and 17 deletions.
41 changes: 24 additions & 17 deletions problems/0123.买卖股票的最佳时机III.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ dp[1] = max(dp[1], dp[0] - prices[i]); 如果dp[1]取dp[1],即保持买入股

## 其他语言版本

Java
### Java

```java
// 版本一
Expand Down Expand Up @@ -221,25 +221,30 @@ class Solution {
// 版本二: 空间优化
class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
int[] dp = new int[5];
dp[1] = -prices[0];
dp[3] = -prices[0];

for (int i = 1; i < len; i++) {
dp[1] = Math.max(dp[1], dp[0] - prices[i]);
dp[2] = Math.max(dp[2], dp[1] + prices[i]);
dp[3] = Math.max(dp[3], dp[2] - prices[i]);
dp[4] = Math.max(dp[4], dp[3] + prices[i]);
int[] dp=new int[4];
// 存储两天的状态就行了
// dp[0]代表第一次买入
dp[0]=-prices[0];
// dp[1]代表第一次卖出
dp[1]=0;
// dp[2]代表第二次买入
dp[2]=-prices[0];
// dp[3]代表第二次卖出
dp[3]=0;
for(int i=1; i<=prices.length; i++){
// 要么保持不变,要么没有就买,有了就卖
dp[0]=Math.max(dp[0], -prices[i-1]);
dp[1]=Math.max(dp[1], dp[0]+prices[i-1]);
// 这已经是第二天了,所以得加上前一天卖出去的价格
dp[2]=Math.max(dp[2], dp[1]-prices[i-1]);
dp[3]=Math.max(dp[3], dp[2]+prices[i-1]);
}

return dp[4];
return dp[3];
}
}
```


Python:
### Python

> 版本一:
```python
Expand Down Expand Up @@ -308,7 +313,7 @@ func max(a,b int)int{



JavaScript
### JavaScript

> 版本一:

Expand Down Expand Up @@ -347,7 +352,7 @@ const maxProfit = prices => {
};
```

Go:
### Go

> 版本一:
```go
Expand Down Expand Up @@ -381,5 +386,7 @@ func max(a, b int) int {
```




-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 comments on commit 5fc3536

Please sign in to comment.