Merge pull request #832 from FangzhouSu/master

更新0121 买股票的最佳时机 添加了JS版本的贪心法
This commit is contained in:
程序员Carl
2021-10-13 18:18:44 +08:00
committed by GitHub

View File

@ -335,6 +335,8 @@ func max(a,b int)int {
JavaScript JavaScript
> 动态规划
```javascript ```javascript
const maxProfit = prices => { const maxProfit = prices => {
const len = prices.length; const len = prices.length;
@ -353,7 +355,19 @@ const maxProfit = prices => {
}; };
``` ```
> 贪心法
```javascript
var maxProfit = function(prices) {
let lowerPrice = prices[0];// 重点是维护这个最小值(贪心的思想)
let profit = 0;
for(let i = 0; i < prices.length; i++){
lowerPrice = Math.min(lowerPrice, prices[i]);// 贪心地选择左面的最小价格
profit = Math.max(profit, prices[i] - lowerPrice);// 遍历一趟就可以获得最大利润
}
return profit;
};
```
----------------------- -----------------------