mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
优化了121动态规划版本二的解题代码^C题代码
This commit is contained in:
@ -249,11 +249,14 @@ class Solution {
|
||||
// 所以我们从 i=1 开始遍历数组,一共有 prices.length 天,
|
||||
// 所以是 i<=prices.length
|
||||
for (int i = 1; i <= prices.length; i++) {
|
||||
int temp = dp[0];
|
||||
// 前一天持有;或当天买入
|
||||
dp[0] = Math.max(temp, -prices[i - 1]);
|
||||
dp[0] = Math.max(dp[0], -prices[i - 1]);
|
||||
// 如果 dp[0] 被更新,那么 dp[1] 肯定会被更新为正数的 dp[1]
|
||||
// 而不是 dp[0]+prices[i-1]==0 的0,
|
||||
// 所以这里使用会改变的dp[0]也是可以的
|
||||
// 当然 dp[1] 初始值为 0 ,被更新成 0 也没影响
|
||||
// 前一天卖出;或当天卖出, 当天要卖出,得前一天持有才行
|
||||
dp[1] = Math.max(dp[1], temp + prices[i - 1]);
|
||||
dp[1] = Math.max(dp[1], dp[0] + prices[i - 1]);
|
||||
}
|
||||
return dp[1];
|
||||
}
|
||||
|
Reference in New Issue
Block a user