20220420, 1min

|
```javascript // 08:54 -> 08:55 // 贪心,每天的正利润相加 var maxProfit = function(prices) { let profit = 0; for (let i = 1; i < prices.length; i++) { profit += Math.max(0, prices[i] - prices[i-1]) } return profit; };

  1. |
  2. | --- |
  3. <a name="NF72s"></a>
  4. ## 20220419, 5min
  5. | <br />```javascript
  6. /**
  7. * @param {number[]} prices
  8. * @return {number}
  9. */
  10. // 13:49 -> 13:54
  11. var maxProfit = function(prices) {
  12. let maxProfit = 0;
  13. for (let i = 1; i < prices.length; i++) {
  14. // maxProfit += (prices[i] - prices[i - 1]) // bug:当天比昨天的价格低的话,可以选择不卖出,所以需要判断利润是否大于0
  15. // const profit = prices[i] - prices[i - 1] // bug:assignment to constant variable
  16. let profit = prices[i] - prices[i - 1]
  17. profit = profit > 0 ? profit : 0;
  18. maxProfit += profit;
  19. }
  20. return maxProfit;
  21. };

知识点
- Math.max(0, prices[i] - prices[i - 1]);let profit = prices[i] - prices[i - 1]; profit = profit > 0 ? profit : 0;的更简单的写法
| | —- |