mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
@ -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 {
|
||||
|
Reference in New Issue
Block a user