Created
May 19, 2019 06:27
-
-
Save SerialForBreakfast/e94b4f906aef5d42331f95cc121a364f to your computer and use it in GitHub Desktop.
Find the largest margin to place a buy and sell order over a day.
This file contains 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
import UIKit | |
let stockPrices:[Int] = [10, 7, 5, 8, 11, 9] | |
func getMaxProfit(from: [Int]) -> Int { | |
var bestProfit: Int = 0 | |
var newSell: Int = 0 | |
var newBuy: Int = Int.max | |
var newSpread: Int = 0 | |
for price in from { | |
if price < newBuy { | |
newSell = price | |
newBuy = price | |
} | |
if price > newSell { | |
newSell = price | |
} | |
newSpread = newSell - newBuy | |
if newSpread > bestProfit { | |
bestProfit = newSpread | |
} | |
} | |
return bestProfit | |
} | |
getMaxProfit(from: stockPrices) | |
//Test Dataset with lagest int preceeding(no short selling) and lower spread after | |
let stockPricesTest:[Int] = [21, 7, 5, 15, 4, 12, 100] | |
getMaxProfit(from: stockPricesTest) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment