Untitled

mail@pastecode.io avatar
unknown
swift
3 years ago
450 B
2
Indexable
Never
import Foundation

func profit(prices: [Int]) -> Int {
    var currentMaximum = 0
    var totalProfit = 0
    for price in prices.reversed() {
        if price > currentMaximum {
            currentMaximum = price
        } else {
            totalProfit += currentMaximum - price
        }
    }
    return totalProfit
}

print(profit(prices: [6, 5, 4, 3, 2, 1]))
print(profit(prices: [1, 6, 5, 10, 8, 7]))
print(profit(prices: [1, 2, 10, 2, 4, 6]))