添加了309和714股票问题一维数组优化空间的java代码

This commit is contained in:
LiHua
2021-11-24 16:12:39 +08:00
parent e9f7683d46
commit 30886018c4
2 changed files with 41 additions and 0 deletions

View File

@ -185,6 +185,29 @@ class Solution {
}
```
```java
// 一维数组优化
class Solution {
public int maxProfit(int[] prices) {
// dp[2]和dp[3]用来存储冷冻期的数据
int[] dp=new int[4];
// 0表示持有1表示卖出
dp[0] = -prices[0];
dp[1] = 0;
for(int i = 1; i <= prices.length; i++){
// 使用临时变量来保存dp[0], dp[2]
// 因为马上dp[0]和dp[2]的数据都会变
int temp = dp[0];
int temp1 = dp[2];
dp[0] = Math.max(dp[0], Math.max(dp[3], dp[1]) - prices[i-1]);
dp[1] = Math.max(dp[1], dp[3]);
dp[2] = temp + prices[i-1];
dp[3] = temp1;
}
return Math.max(dp[3],Math.max(dp[1],dp[2]));
}
}
```
Python

View File

@ -195,8 +195,26 @@ class Solution { // 动态规划
}
```
```java
// 一维数组优化
class Solution {
public int maxProfit(int[] prices, int fee) {
int[] dp = new int[2];
dp[0] = -prices[0];
dp[1] = 0;
for (int i = 1; i <= prices.length; i++) {
dp[0] = Math.max(dp[0], dp[1] - prices[i - 1]);
dp[1] = Math.max(dp[1], dp[0] + prices[i - 1] - fee);
}
return dp[1];
}
}
```
Python
```python
class Solution: # 贪心思路
def maxProfit(self, prices: List[int], fee: int) -> int: