Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 86bbd55

Browse files
Merge pull request youngyangyang04#2130 from Lozakaka/patch-22
新增java 2*4 solution 並附上 對於2-D array, 1-D array的分析
2 parents 22c2ce5 + 88162c3 commit 86bbd55

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

‎problems/0309.最佳买卖股票时机含冷冻期.md‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,33 @@ class Solution {
200200
}
201201
}
202202
```
203-
203+
```java
204+
//using 2*4 array for space optimization
205+
//這裡稍微說一下,我在LeetCode提交的時候,2*4 2-D array的performance基本上和下面的1-D array performance差不多
206+
//都是time: 1ms, space: 40.X MB (其實 length*4 的 2-D array也僅僅是space:41.X MB,看起來不多)
207+
//股票累的DP題目大致上都是這樣,就當作是一個延伸就好了。真的有人問如何優化,最起碼有東西可以講。
208+
class Solution {
209+
/**
210+
1. [i][0] holding the stock
211+
2. [i][1] after cooldown but stil not buing the stock
212+
3. [i][2] selling the stock
213+
4. [i][3] cooldown
214+
*/
215+
public int maxProfit(int[] prices) {
216+
int len = prices.length;
217+
int dp[][] = new int [2][4];
218+
dp[0][0] = -prices[0];
219+
220+
for(int i = 1; i < len; i++){
221+
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]);
222+
dp[i % 2][1] = Math.max(dp[(i - 1) % 2][1], dp[(i - 1) % 2][3]);
223+
dp[i % 2][2] = dp[(i - 1) % 2][0] + prices[i];
224+
dp[i % 2][3] = dp[(i - 1) % 2][2];
225+
}
226+
return Math.max(Math.max(dp[(len - 1) % 2][1], dp[(len - 1) % 2][2]), dp[(len - 1) % 2][3]);
227+
}
228+
}
229+
```
204230
```java
205231
// 一维数组优化
206232
class Solution {

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /