mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
Merge pull request #832 from FangzhouSu/master
更新0121 买股票的最佳时机 添加了JS版本的贪心法
This commit is contained in:
@ -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;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
|
Reference in New Issue
Block a user