mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
增加 0122.买卖股票的最佳时机II go版本
增加 0122.买卖股票的最佳时机II go版本
This commit is contained in:
@ -188,7 +188,40 @@ class Solution:
|
||||
```
|
||||
|
||||
Go:
|
||||
```golang
|
||||
//贪心算法
|
||||
func maxProfit(prices []int) int {
|
||||
var sum int
|
||||
for i := 1; i < len(prices); i++ {
|
||||
// 累加每次大于0的交易
|
||||
if prices[i]-prices[i-1] > 0 {
|
||||
sum += prices[i]-prices[i-1]
|
||||
}
|
||||
}
|
||||
return sum
|
||||
}
|
||||
```
|
||||
|
||||
```golang
|
||||
//确定售卖点
|
||||
func maxProfit(prices []int) int {
|
||||
var result,buy int
|
||||
prices=append(prices,0)//在price末尾加个0,防止price一直递增
|
||||
/**
|
||||
思路:检查后一个元素是否大于当前元素,如果小于,则表明这是一个售卖点,当前元素的值减去购买时候的值
|
||||
如果不小于,说明后面有更好的售卖点,
|
||||
**/
|
||||
for i:=0;i<len(prices)-1;i++{
|
||||
if prices[i]>prices[i+1]{
|
||||
result+=prices[i]-prices[buy]
|
||||
buy=i+1
|
||||
}else if prices[buy]>prices[i]{//更改最低购买点
|
||||
buy=i
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
```
|
||||
|
||||
Javascript:
|
||||
```Javascript
|
||||
|
Reference in New Issue
Block a user