Merge pull request #2129 from Lozakaka/patch-21

新增java 2*2 array solution
This commit is contained in:
程序员Carl 2023-06-28 10:04:56 +08:00 committed by GitHub
commit 22c2ce57f5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 19 additions and 0 deletions

View File

@ -154,6 +154,25 @@ class Solution {
return dp[1]; 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 Python