mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加了309和714股票问题一维数组优化空间的java代码
This commit is contained in:
@ -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:
|
||||
|
||||
|
@ -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:
|
||||
|
Reference in New Issue
Block a user