Merge pull request #2127 from Lozakaka/patch-19

新增JAVA 2*2數組
This commit is contained in:
程序员Carl 2023-06-26 10:36:54 +08:00 committed by GitHub
commit 0829e1f68e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 17 additions and 0 deletions

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
// 优化空间
class Solution {