美文网首页
121.股票最佳买卖

121.股票最佳买卖

作者: faterman | 来源:发表于2021-04-29 11:10 被阅读0次

1.暴力两层循环,思路没啥问题,时间LeetCode上会超时

class Solution {
    func maxProfit(_ prices: [Int]) -> Int {
        var maxProfit = 0
        for cursor_0 in 0..<prices.count {
            for cursor_1 in (cursor_0 + 1)..<prices.count {
                if (prices[cursor_1] - prices[cursor_0]) > maxProfit {
                    maxProfit = prices[cursor_1] - prices[cursor_0]
                }
            }
        }
        return maxProfit
    }
}
  1. 换一个思路,每个时间卖出的最大价格都是和前面最小价格的差,多用一个变量记录一下前面的最小值实现复杂度降到O(n)
class Solution {
    func maxProfit(_ prices: [Int]) -> Int {
        var minPrice = Int.max
        var maxProfit = 0
        for cursor in 0..<prices.count {
            if prices[cursor] < minPrice {
                minPrice = prices[cursor]
            }else if prices[cursor] - minPrice > maxProfit {
                maxProfit = prices[cursor] - minPrice
            }
        }
        return maxProfit
    }
}

相关文章

网友评论

      本文标题:121.股票最佳买卖

      本文链接:https://www.haomeiwen.com/subject/ctnirltx.html