新增java一維數組解法(很卡哥邏輯一致)

原本的那個版本不知道在寫什麼
This commit is contained in:
Terry Liu
2023-06-14 18:30:56 -04:00
committed by GitHub
parent ec6c3e9d7e
commit b1e8b17eb1

View File

@ -227,7 +227,7 @@ class Solution {
}
}
//版本三:一维 dp数组
//版本三:一维 dp数组 (下面有和卡哥邏輯一致的一維數組JAVA解法)
class Solution {
public int maxProfit(int k, int[] prices) {
if(prices.length == 0){
@ -259,6 +259,41 @@ class Solution {
}
}
```
```JAVA
class Solution {
public int maxProfit(int k, int[] prices) {
//edge cases
if(prices.length == 0 || k == 0)
return 0;
int dp[] = new int [k * 2 + 1];
//和卡哥邏輯一致,奇數天購入股票,故初始化只初始化奇數天。
for(int i = 1; i < 2 * k + 1; i += 2){
dp[i] = -prices[0];
}
for(int i = 1; i < prices.length; i++){ //i 從 1 開始,因爲第 i = 0 天已經透過初始化完成了。
for(int j = 1; j < 2 * k + 1; j++){ //j 從 1 開始,因爲第 j = 0 天已經透過初始化完成了。
//奇數天購買
if(j % 2 == 1)
dp[j] = Math.max(dp[j], dp[j - 1] - prices[i]);
//偶數天賣出
else
dp[j] = Math.max(dp[j], dp[j - 1] + prices[i]);
}
//打印DP數組
//for(int x : dp)
// System.out.print(x +", ");
//System.out.println();
}
//return 第2 * k次賣出的獲利。
return dp[2 * k];
}
}
```
Python: