@@ -188,7 +188,7 @@ dp[1] = max(dp[1], dp[0] - prices[i]); 如果dp[1]取dp[1],即保持买入股
188
188
189
189
## 其他语言版本
190
190
191
- Java:
191
+ ### Java
192
192
193
193
``` java
194
194
// 版本一
@@ -221,25 +221,30 @@ class Solution {
221
221
// 版本二: 空间优化
222
222
class Solution {
223
223
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 ]);
234
241
}
235
-
236
- return dp[4 ];
242
+ return dp[3 ];
237
243
}
238
244
}
239
245
```
240
246
241
-
242
- Python:
247
+ ### Python
243
248
244
249
> 版本一:
245
250
```python
@@ -308,7 +313,7 @@ func max(a,b int)int{
308
313
309
314
310
315
311
- JavaScript:
316
+ ### JavaScript
312
317
313
318
> 版本一:
314
319
@@ -347,7 +352,7 @@ const maxProfit = prices => {
347
352
};
348
353
```
349
354
350
- Go:
355
+ ### Go
351
356
352
357
> 版本一:
353
358
``` go
@@ -381,5 +386,7 @@ func max(a, b int) int {
381
386
```
382
387
383
388
389
+
390
+
384
391
-----------------------
385
392
<div align =" center " ><img src =https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width =500 > </img ></div >
0 commit comments