0
点赞
收藏
分享

微信扫一扫

LeetCode 打卡 Day 49 —— 买卖股票的最佳时机

乌龙茶3297 2022-04-22 阅读 61
leetcode

1、题目

  

2、题解

题目还是较为简单的,暴力方法很容易想到,使用一个二重遍历,固定数组中每一个数字然后向后进行遍历,保存差的最大值。但是总感觉有能够优于暴力解法的方法,即在遍历的过程中保存已遍历过的数字中的最小值,用当前值减去最小值即当前值能取得的最大利润。实现代码如下

func maxProfit(prices []int) int {
    profit:=0
    minP:=math.MaxInt32
    getMin:=func(a, b int) int {
        if a>b {
            return b
        }else { return a }
    }
    getMax:=func(a, b int) int {
        if a<=b {
            return b
        }else { return a }
    }

    for i:=0; i<len(prices); i++ {
        minP=getMin(minP, prices[i])
        profit=getMax(profit, prices[i]-minP)
    }
    return profit
}

提交结果如下

举报

相关推荐

0 条评论