Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5fc3536

Browse files
统一了123优化空间写法的java解题代码格式
1 parent eacf15d commit 5fc3536

File tree

1 file changed

+24
-17
lines changed

1 file changed

+24
-17
lines changed

‎problems/0123.买卖股票的最佳时机III.md

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ dp[1] = max(dp[1], dp[0] - prices[i]); 如果dp[1]取dp[1],即保持买入股
188188

189189
## 其他语言版本
190190

191-
Java:
191+
### Java
192192

193193
```java
194194
// 版本一
@@ -221,25 +221,30 @@ class Solution {
221221
// 版本二: 空间优化
222222
class Solution {
223223
public int maxProfit(int[] prices) {
224-
int len = prices.length;
225-
int[] dp = new int[5];
226-
dp[1] = -prices[0];
227-
dp[3] = -prices[0];
228-
229-
for (int i = 1; i < len; i++) {
230-
dp[1] = Math.max(dp[1], dp[0] - prices[i]);
231-
dp[2] = Math.max(dp[2], dp[1] + prices[i]);
232-
dp[3] = Math.max(dp[3], dp[2] - prices[i]);
233-
dp[4] = Math.max(dp[4], dp[3] + prices[i]);
224+
int[] dp=new int[4];
225+
// 存储两天的状态就行了
226+
// dp[0]代表第一次买入
227+
dp[0]=-prices[0];
228+
// dp[1]代表第一次卖出
229+
dp[1]=0;
230+
// dp[2]代表第二次买入
231+
dp[2]=-prices[0];
232+
// dp[3]代表第二次卖出
233+
dp[3]=0;
234+
for(int i=1; i<=prices.length; i++){
235+
// 要么保持不变,要么没有就买,有了就卖
236+
dp[0]=Math.max(dp[0], -prices[i-1]);
237+
dp[1]=Math.max(dp[1], dp[0]+prices[i-1]);
238+
// 这已经是第二天了,所以得加上前一天卖出去的价格
239+
dp[2]=Math.max(dp[2], dp[1]-prices[i-1]);
240+
dp[3]=Math.max(dp[3], dp[2]+prices[i-1]);
234241
}
235-
236-
return dp[4];
242+
return dp[3];
237243
}
238244
}
239245
```
240246

241-
242-
Python:
247+
### Python
243248

244249
> 版本一:
245250
```python
@@ -308,7 +313,7 @@ func max(a,b int)int{
308313

309314

310315

311-
JavaScript:
316+
### JavaScript
312317

313318
> 版本一:
314319

@@ -347,7 +352,7 @@ const maxProfit = prices => {
347352
};
348353
```
349354

350-
Go:
355+
### Go
351356

352357
> 版本一:
353358
```go
@@ -381,5 +386,7 @@ func max(a, b int) int {
381386
```
382387

383388

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

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /