mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 0188.买卖股票的最佳时机IV.md
This commit is contained in:
@ -196,7 +196,7 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 版本二: 空间优化
|
// 版本二: 二维 dp数组
|
||||||
class Solution {
|
class Solution {
|
||||||
public int maxProfit(int k, int[] prices) {
|
public int maxProfit(int k, int[] prices) {
|
||||||
if (prices.length == 0) return 0;
|
if (prices.length == 0) return 0;
|
||||||
@ -220,6 +220,25 @@ class Solution {
|
|||||||
return dp[len - 1][k*2];
|
return dp[len - 1][k*2];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//版本三:一维 dp数组
|
||||||
|
class Solution {
|
||||||
|
public int maxProfit(int k, int[] prices) {
|
||||||
|
//在版本二的基础上,由于我们只关心前一天的股票买入情况,所以只存储前一天的股票买入情况
|
||||||
|
if(prices.length==0)return 0;
|
||||||
|
int[] dp=new int[2*k+1];
|
||||||
|
for (int i = 1; i <2*k ; i+=2) {
|
||||||
|
dp[i]=-prices[0];
|
||||||
|
}
|
||||||
|
for (int i = 0; i <prices.length ; i++) {
|
||||||
|
for (int j = 1; j <2*k ; j+=2) {
|
||||||
|
dp[j]=Math.max(dp[j],dp[j-1]-prices[i]);
|
||||||
|
dp[j+1]=Math.max(dp[j+1],dp[j]+prices[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return dp[2*k];
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user