不太会用动态规划,用了个贪心,看不懂可以留言哈
package main
import "math"
/**
*
* @param prices int整型一维数组
* @return int整型
*/
func maxProfit(prices []int) int {
// write code here
if len(prices) == 0 {
return 0
}
maxCut := 0 // 记录每个时刻最大差值(只能往前减)
lens := len(prices)
bottom := prices[0] //初始时最底部值置为prices[0]
for i := 1; i < lens; i++ {
if prices[i] > prices[i-1] { //如果呈递增态,一直往后遍历至转折点
continue
} else { //转折点
maxCut = int(math.Max(float64(prices[i-1]-bottom), float64(maxCut))) //更新最大差值
bottom = int(math.Min(float64(prices[i]), float64(bottom))) //更新底部值
}
}
maxCut = int(math.Max(float64(prices[lens-1]-bottom), float64(maxCut))) //若最后有一段递增,需要额外处理
return maxCut
}

京公网安备 11010502036488号