更新0121 买股票的最佳时机 添加了JS版本的贪心法

第一次向卡哥的LeetCode-Master提交代码 激动.jpg! 对于这道题 第一次接触这道题的时候使用的暴力解一跑直接超时 后来看了题解中使用的贪心算法惊为天人 觉得好有道理!看到这道题里还没有 就加入了一下~希望以后可以为卡哥的项目共享更多代码!
This commit is contained in:
Vl_Coding_lover
2021-10-10 16:08:17 +08:00
parent b5dcc5583d
commit da254e87ad

View File

@ -335,6 +335,8 @@ func max(a,b int)int {
JavaScript
> 动态规划
```javascript
const maxProfit = prices => {
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;
};
```
-----------------------