Published: 24 Dec 2018 › Updated: 24 Dec 2018

One algorithm a day. Write a function that returns best profit you could made from trading.
Write an efficient function that takes stockPrices and returns the best profit I could have made from one purchase and one sale of one share of Apple stock yesterday.
func getMaxProfit(_ prices:[Double])->Double{
//we need to track a difference
guard prices.count > 0 else{
return 0
}
var priceDifference = 0.0
for time in 0..<prices.count{
let price = prices[time]
for laterTime in time + 1..<prices.count{
let laterPrice = prices[laterTime]
if (laterPrice - price) > priceDifference{
priceDifference = (laterPrice - price)
}
}
}
return priceDifference
}
let stockPrices:[Double] = [10, 7, 5, 8, 11, 9]
getMaxProfit(stockPrices)
Leave One algorithm a day. Write a function that returns best profit you could made from trading. to:
Read more #swift posts
Best Posts From cryptoizotx
We have not curated any of cryptoizotx's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From cryptoizotx
- Keyframe animations with Swift
- One algorithm a day: Keeping track of the largest element in a stack
- One algorithm a day. Write a function that returns best profit you could made from trading.
- One algorithm a day: floor of the square root of the input
- iOS Interview: Delegation Pattern in Swift
- Delegation Pattern in Objective-C
- Swift Interview Questions Recursion: Print numbers from 0 to n without using for loop.
- Bitwise Operators in Swift
- S O L I D Principle Rules in iOS
- Decentralized Programmer: Solidity 101