買賣股票的最佳時機

class Solution {
    func maxProfit(_ prices: [Int]) -> Int {
        if (prices.count == 0 || prices.count == 1 || (prices.count == 2 && prices[0] >= prices[1])) {
            return 0
        }
        
        if (prices.count == 2 && prices[0] < prices[1]) {
            return prices[1] - prices[0]
        }
        
        var total = 0
        var lower = prices[0]
        var higher = lower

        for i in 1...prices.count - 1 {
            print(prices[i], total, lower, higher)
            if (lower >= prices[i]) {
                lower = prices[i]
                higher = prices[i]
            } else if (i == prices.count - 1) {
                higher = prices[i]
                total += higher - lower
            } else if (prices[i+1] < prices[i]) {
                higher = prices[i]
                total += higher - lower
                lower = prices[i+1]
                higher = lower
            }
                
        }
        return total

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章