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;
};
|
| --- |
<a name="NF72s"></a>
## 20220419, 5min
| <br />```javascript
/**
* @param {number[]} prices
* @return {number}
*/
// 13:49 -> 13:54
var maxProfit = function(prices) {
let maxProfit = 0;
for (let i = 1; i < prices.length; i++) {
// maxProfit += (prices[i] - prices[i - 1]) // bug:当天比昨天的价格低的话,可以选择不卖出,所以需要判断利润是否大于0
// const profit = prices[i] - prices[i - 1] // bug:assignment to constant variable
let profit = prices[i] - prices[i - 1]
profit = profit > 0 ? profit : 0;
maxProfit += profit;
}
return maxProfit;
};
知识点
- Math.max(0, prices[i] - prices[i - 1]);
是let profit = prices[i] - prices[i - 1]; profit = profit > 0 ? profit : 0;
的更简单的写法
|
| —- |