mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
@ -227,7 +227,7 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//版本三:一维 dp数组
|
//版本三:一维 dp数组 (下面有和卡哥邏輯一致的一維數組JAVA解法)
|
||||||
class Solution {
|
class Solution {
|
||||||
public int maxProfit(int k, int[] prices) {
|
public int maxProfit(int k, int[] prices) {
|
||||||
if(prices.length == 0){
|
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:
|
Python:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user