day 42 |● 121. 买卖股票的最佳时机 ● 122.买卖股票的最佳时机II
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
}