买卖股票的最佳时机 I
func maxProfit(prices []int) int {
maxProfit := 0
minPrice := math.MaxInt64
for _, v := range prices {
minPrice = mymin(minPrice, v)
maxProfit = mymax(maxProfit, v-minPrice)
}
return maxProfit
}
func mymin(x, y int) int {
if x > y {
return y
}
return x
}
func mymax(x, y int) int {
if x > y {
return x
}
return y
}
买卖股票的最佳时机 II
func maxProfit(prices []int) int {
cur, max := 0, 0
for i := 1; i < len(prices); i++ {
cur = mymax(cur, cur+prices[i]-prices[i-1])
max = mymax(cur, max)
}
return max
}
func mymax(x, y int) int {
if x > y {
return x
}
return y
}
买卖股票的最佳时机 III
/**
只能进行两次交易,因此一共有四个状态,互相之间转移
*/
func maxProfit(prices []int) int {
b1, b2 := math.MinInt32, math.MinInt32
s1, s2 := 0, 0
for i := 0; i < len(prices); i++ {
b1 = max(b1, -prices[i])
s1 = max(s1, b1+prices[i])
b2 = max(b2, s1-prices[i])
s2 = max(s2, b2+prices[i])
}
return s2
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
网友评论