Created
January 6, 2022 17:26
-
-
Save faganello60/47ea9f548bc7398bf68faf55ff3742c4 to your computer and use it in GitHub Desktop.
StockPrice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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