Skip to content

Commit e9f7683

Browse files
committed
更换了188一维数组java解题代码
1 parent 5fc3536 commit e9f7683

File tree

1 file changed

+23
-10
lines changed

1 file changed

+23
-10
lines changed

problems/0188.买卖股票的最佳时机IV.md

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -222,19 +222,32 @@ class Solution {
222222
//版本三:一维 dp数组
223223
class Solution {
224224
public int maxProfit(int k, int[] prices) {
225-
//在版本二的基础上,由于我们只关心前一天的股票买入情况,所以只存储前一天的股票买入情况
226-
if(prices.length==0)return 0;
227-
int[] dp=new int[2*k+1];
228-
for (int i = 1; i <2*k ; i+=2) {
229-
dp[i]=-prices[0];
225+
if(prices.length == 0){
226+
return 0;
230227
}
231-
for (int i = 0; i <prices.length ; i++) {
232-
for (int j = 1; j <2*k ; j+=2) {
233-
dp[j]=Math.max(dp[j],dp[j-1]-prices[i]);
234-
dp[j+1]=Math.max(dp[j+1],dp[j]+prices[i]);
228+
if(k == 0){
229+
return 0;
230+
}
231+
// 其实就是123题的扩展,123题只用记录2天的状态
232+
// 这里记录k天的状态就行了
233+
// 每天都有买入,卖出两个状态,所以要乘 2
234+
int[] dp = new int[2 * k];
235+
// 按123题解题格式那样,做一个初始化
236+
for(int i = 0; i < dp.length / 2; i++){
237+
dp[i * 2] = -prices[0];
238+
}
239+
for(int i = 1; i <= prices.length; i++){
240+
dp[0] = Math.max(dp[0], -prices[i - 1]);
241+
dp[1] = Math.max(dp[1], dp[0] + prices[i - 1]);
242+
// 还是与123题一样,与123题对照来看
243+
// 就很容易啦
244+
for(int j = 2; j < dp.length; j += 2){
245+
dp[j] = Math.max(dp[j], dp[j - 1] - prices[i-1]);
246+
dp[j + 1] = Math.max(dp[j + 1], dp[j] + prices[i - 1]);
235247
}
236248
}
237-
return dp[2*k];
249+
// 返回最后一天卖出状态的结果就行了
250+
return dp[dp.length - 1];
238251
}
239252
}
240253
```

0 commit comments

Comments
 (0)