121.股票最佳买卖

2021-04-29  本文已影响0人  faterman

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
    }
}
上一篇下一篇

猜你喜欢

热点阅读