mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 02:53:31 +08:00
新增java 2*4 solution 並附上 對於2-D array, 1-D array的分析
This commit is contained in:
@ -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 {
|
||||
|
Reference in New Issue
Block a user