新增JAVA 2*2數組

//DP using 2*2 Array (下方還有使用一維滾動數組的更優化版本)
This commit is contained in:
Terry Liu
2023-06-06 19:25:22 -04:00
committed by GitHub
parent 46a81f2073
commit 9287b6be6f

View File

@ -154,7 +154,24 @@ class Solution
} }
} }
``` ```
```java
//DP using 2*2 Array (下方還有使用一維滾動數組的更優化版本)
class Solution {
public int maxProfit(int[] prices) {
int dp[][] = new int [2][2];
//dp[i][0]: holding the stock
//dp[i][1]: not holding the stock
dp[0][0] = - prices[0];
dp[0][1] = 0;
for(int i = 1; i < prices.length; i++){
dp[i % 2][0] = Math.max(dp[(i - 1) % 2][0], dp[(i - 1) % 2][1] - prices[i]);
dp[i % 2][1] = Math.max(dp[(i - 1) % 2][1], dp[(i - 1) % 2][0] + prices[i]);
}
return dp[(prices.length - 1) % 2][1];
}
}
```
```java ```java
// 优化空间 // 优化空间
class Solution { class Solution {