/** * @param {number[]} prices * @return {number} */ var maxProfit = function (prices) { let ans = 0; for (let i = 1; i < prices.length; i++) { let profit = prices[i] - prices[i - 1]; if (profit > 0) { ans += profit; } } return ans; };
官方题解
动态规划法
dp[i][j]表示第i天手里有无股票(j=0无股票,1有股票)
dp[i][0]=max{dp[i−1][0],dp[i−1][1]+prices[i]}
dp[i][1]=max{dp[i−1][1],dp[i−1][0]−prices[i]}
代码
1 2 3 4 5 6 7 8 9 10
var maxProfit = function (prices) { const n = prices.length; const dp = newArray(n).fill(0).map((v) =>newArray(2).fill(0)); (dp[0][0] = 0), (dp[0][1] = -prices[0]); for (let i = 1; i < n; ++i) { dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]); dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]); } return dp[n - 1][0]; };
觉得有点简单问题复杂化了
hinak0
Recording personal notes, covering various aspects.