mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
统一了123优化空间写法的java解题代码格式
This commit is contained in:
@ -188,7 +188,7 @@ dp[1] = max(dp[1], dp[0] - prices[i]); 如果dp[1]取dp[1],即保持买入股
|
||||
|
||||
## 其他语言版本
|
||||
|
||||
Java:
|
||||
### Java
|
||||
|
||||
```java
|
||||
// 版本一
|
||||
@ -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
|
||||
@ -308,7 +313,7 @@ func max(a,b int)int{
|
||||
|
||||
|
||||
|
||||
JavaScript:
|
||||
### JavaScript
|
||||
|
||||
> 版本一:
|
||||
|
||||
@ -347,7 +352,7 @@ const maxProfit = prices => {
|
||||
};
|
||||
```
|
||||
|
||||
Go:
|
||||
### Go
|
||||
|
||||
> 版本一:
|
||||
```go
|
||||
@ -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>
|
||||
|
Reference in New Issue
Block a user