软件开发公司服务,重庆seo搜索引擎优化推荐,个人什么取消网站备案,郑州做网站优化公121. 买卖股票的最佳时机
dp数组需要记录两种状态#xff0c;一种是当天时手中还持有股票#xff0c;一种是当天时手中已卖出股票。
func maxProfit(prices []int) int {dp : make([][]int, len(prices))dp[0] []int{-prices[0], 0}for i : 1; i len(prices); i{val0…121. 买卖股票的最佳时机
dp数组需要记录两种状态一种是当天时手中还持有股票一种是当天时手中已卖出股票。
func maxProfit(prices []int) int {dp : make([][]int, len(prices))dp[0] []int{-prices[0], 0}for i : 1; i len(prices); i{val0 : max(dp[i - 1][0], -prices[i])val1 : max(dp[i - 1][1], prices[i] dp[i - 1][0]) dp[i] []int{val0,val1}} return dp[len(prices) - 1][1]
}func max(a ,b int)int{if a b{return b}return a
}122.买卖股票的最佳时机II
持有股票的状态可以是当天才持有也可以是之前就持有 卖出的状态同理
func maxProfit(prices []int) int {dp : make([][]int, len(prices))dp[0] []int{-prices[0], 0}for i : 1; i len(prices); i{val0 : max(dp[i - 1][0], dp[i - 1][1] - prices[i])val1 : max(dp[i - 1][0] prices[i], dp[i - 1][1])dp[i] []int{val0, val1}}return dp[len(prices) - 1][1]
}
func max(a, b int)int{if a b{return b}return a
}