
法一:贪心算法
解题思路:
用变量buyPrice记录最低价格,如果出现更低的价格,更新最低价格,如果当前价格减去最低价格buyPrice大于收益,更新收益。
func maxProfit(prices []int) int {
if len(prices)==0{
return 0
}
buyPrice:=prices[0]
maxProfit:=0
for i:=1;i<len(prices);i++{
if prices[i]<buyPrice{
buyPrice=prices[i]
}else if prices[i]-buyPrice>maxProfit{
maxProfit=prices[i]-buyPrice
}
}
return maxProfit
}
该代码实现了一个计算股票交易中能获得的最大利润的贪心算法。通过遍历股票价格数组,记录最低购买价格,并在价格上升超过最低价与当前价的差值时更新最大利润。
419

被折叠的 条评论
为什么被折叠?



