新增java 2*2 array solution

This commit is contained in:
Terry Liu
2023-06-09 18:11:29 -04:00
committed by GitHub
parent f83bbd493c
commit 652fa2bbb0

View File

@ -154,6 +154,25 @@ class Solution {
return dp[1];
}
}
```Java
//使用 2*2 array
class Solution {
public int maxProfit(int[] prices, int fee) {
int dp[][] = new int[2][2];
int len = prices.length;
//[i][0] = holding the stock
//[i][1] = not holding the stock
dp[0][0] = -prices[0];
for(int i = 1; i < len; 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] - fee);
}
return dp[(len - 1) % 2][1];
}
}
```
```
Python