Skip to content

Commit

Permalink
Merge pull request youngyangyang04#2130 from Lozakaka/patch-22
Browse files Browse the repository at this point in the history
新增java 2*4 solution 並附上 對於2-D array, 1-D array的分析
  • Loading branch information
youngyangyang04 authored Jun 28, 2023
2 parents 22c2ce5 + 88162c3 commit 86bbd55
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion problems/0309.最佳买卖股票时机含冷冻期.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,33 @@ class Solution {
}
}
```

```java
//using 2*4 array for space optimization
//這裡稍微說一下,我在LeetCode提交的時候,2*4 2-D array的performance基本上和下面的1-D array performance差不多
//都是time: 1ms, space: 40.X MB (其實 length*4 的 2-D array也僅僅是space:41.X MB,看起來不多)
//股票累的DP題目大致上都是這樣,就當作是一個延伸就好了。真的有人問如何優化,最起碼有東西可以講。
class Solution {
/**
1. [i][0] holding the stock
2. [i][1] after cooldown but stil not buing the stock
3. [i][2] selling the stock
4. [i][3] cooldown
*/
public int maxProfit(int[] prices) {
int len = prices.length;
int dp[][] = new int [2][4];
dp[0][0] = -prices[0];

for(int i = 1; i < len; i++){
dp[i % 2][0] = Math.max(Math.max(dp[(i - 1) % 2][0], dp[(i - 1) % 2][1] - prices[i]), dp[(i - 1) % 2][3] - prices[i]);
dp[i % 2][1] = Math.max(dp[(i - 1) % 2][1], dp[(i - 1) % 2][3]);
dp[i % 2][2] = dp[(i - 1) % 2][0] + prices[i];
dp[i % 2][3] = dp[(i - 1) % 2][2];
}
return Math.max(Math.max(dp[(len - 1) % 2][1], dp[(len - 1) % 2][2]), dp[(len - 1) % 2][3]);
}
}
```
```java
// 一维数组优化
class Solution {
Expand Down

0 comments on commit 86bbd55

Please sign in to comment.