leetCode

要求:

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。

注意你不能在买入股票前卖出股票。

class Solution {
    func maxProfit(_ prices: [Int]) -> Int {
        var priceDiff: [Int] = []
        for (index, value) in prices.enumerated() {
            if index > 0 {
                priceDiff.append(value - prices[index - 1])
            }
        }
        
        var maxProfits = 0;
        var profits = 0;
        
        
        for value in priceDiff {
            if profits + value > 0 {
                profits += value
            }else {
                profits = 0
            }
            
            if profits > maxProfits {
                maxProfits = profits
            }
        }
        return maxProfits
    }
}
原文地址:https://www.cnblogs.com/kaisi/p/10167383.html