买卖股票的最佳时机 I LeetCode121

买卖股票的最佳时机

简单,注释都可不用
前i天的最大收益 = max{前i-1天的最大收益,第i天的价格-前i-1天中的最小价格

func maxProfit(prices []int) int {
    max:=0
    prof:=0
    for j:=0;j<len(prices);j++{
        for i:=0;i<j;i++{
            if prices[j]-prices[i]>prof{
                prof=prices[j]-prices[i]
            }
            if max<prof{
                max=prof
            }
        }
    }
    return max
}

更新下,这个更优秀

func maxProfit(prices []int) int {
    length := len(prices)
    if length <= 1 {
        return 0
    }
    minprice := prices[0] // 记录最小的价格,,,哎哎哎
    maxprofit := 0 // 记录最大利润
    for i := 1; i < length; i++ {
        if prices[i] < minprice {
            minprice = prices[i]
        }
        // 前i天的最大收益 = max{前i-1天的最大收益,第i天的价格 - 前i-1天中的最小价格}
        maxprofit = max(maxprofit, prices[i] - minprice)
    }
    return maxprofit 
}

func max(x, y int) int {
    if x>y {
        return x
    }
    return y
}
posted @ 2020-07-27 17:38  柠檬橘  阅读(116)  评论(0编辑  收藏  举报