Skip to content

Instantly share code, notes, and snippets.

@faganello60
Created January 6, 2022 17:26
Show Gist options
  • Save faganello60/47ea9f548bc7398bf68faf55ff3742c4 to your computer and use it in GitHub Desktop.
Save faganello60/47ea9f548bc7398bf68faf55ff3742c4 to your computer and use it in GitHub Desktop.
StockPrice
/*
Given a array of numbers representing the stock prices of a company in chronological order, write a function that calculates the maximum profit you could have made from buying and selling that stock once. You must buy before you can sell it.
For example, given [9, 11, 8, 5, 7, 10], you should return 5, since you could buy the stock at 5 dollars and sell it at 10 dollars.
*/
func stockPrice(stocks: [Int]) -> Int {
var max = 0
for(i, buy) in stocks.enumerated() {
for sell in i+1..<stocks.count {
let profit = stocks[sell] - buy
if profit > max { max = profit }
}
}
return max
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment