var maxProfit = function (prices) { prices.unshift(Number.MAX_VALUE) prices.push(Number.MIN_SAFE_INTEGER) let result = 0 let minVal = prices[0] for (let i = 1; i < prices.length; ++i) { if (prices[i] > prices[i - 1]) { continue } result += Math.max(0, prices[i - 1] - minVal) minVal = prices[i] } return result }
进一步简化思路,最大利润 = 每天与前一天正向价差的累加
1 2 3 4 5 6 7 8 9 10 11
var maxProfit = function (prices) { let result = 0 let prevPrice = Number.MAX_VALUE for (const curPrice of prices) { if (curPrice > prevPrice) { result += curPrice - prevPrice } prevPrice = curPrice } return result }