目录
题目描述
链接: 力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
实现
func maxProfit(prices []int) int {
n := len(prices)
in, profit := 0, 0 // in买入位置
for j := 1; j < n; j++ {
if prices[j] < prices[in] {
in = j
continue
}
if prices[j]-prices[in] > profit {
profit = prices[j] - prices[in] // 当前情况下卖出时的利润
}
}
return profit
}
验证
var nums1 = []int{7, 1, 5, 3, 6, 4}
n1 := maxProfit(nums1)
fmt.Println(n1) // 5
var nums2 = []int{7, 6, 4, 3, 1}
n2 := maxProfit(nums2)
fmt.Println(n2) // 0
var nums3 = []int{5, 6, 5, 3, 9, 8}
n3 := maxProfit(nums3)
fmt.Println(n3) // 6
时:O(n)
空 :常数个变量,O(1)
提交结果
解答可能并不唯一,仅供参考哦!