Maximum Gain

Given an array of price fluctuations throughout the day for a stock in the stock market, find the buy and sell price that would have yielded the maximum gain for the day.

Hint: the maximum gain is not necessarily related to the high price or low price of the day. To make a gain, a buy needs to occur before a sell, and the buy price must be lower than the sell price.

This can be solved in one pass through the prices, or O(n).

var buy = 0
var sell = 0
var max = 0
var low = prices[0]
var high = prices[0]

for i in 1 ..< prices.count {
  let price = prices[i]
  if price - low > max {
    max = price - low
    sell = price
    buy = low
  if price < low {
    low = price
  if price > high {
    high = price

print("buy \(buy) sell \(sell)")
print("low \(low) high \(high)")
print("max \(max)")

Scroll to top