leetCode - 買賣股票的最佳時機(Swift實現)
阿新 • • 發佈:2018-12-24
要求:
給定一個數組,它的第 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 } }