Find maximum potential profit from an array of stock prices - pure-functional immutable Scala solution by William Narmontas (Scala Algorithm #2)

Problem

Return a maximum potential profit given an array of stock prices - based on one buy followed by one sell. In case there is no way to profit, return None. Here we look for an efficient solution (\(O(n)\)). This problem is known as:

View on Scastie (online Scala code playground, in a new window) if you would like to play around with this code, run it, add new test cases, all from your web browser without installing Scala.

def findMaximumProfit(stockPrices: Array[Int]): Option[Int] = {
  val maximumSellPricesFromIonward = stockPrices.view
    .scanRight(0) {
      case (maximumPriceSoFar, dayPrice) =>
        Math.max(maximumPriceSoFar, dayPrice)
    }
    .toArray

  /**
  We cannot sell on the same day, so for each day, we want not the maximum
  sale price on that day forward, but from the next day forward.
  **/
  val maximumSellPricesAfterI = maximumSellPricesFromIonward.drop(1)

  if (stockPrices.length < 2) None
  else
    stockPrices
      .zip(maximumSellPricesAfterI)
      .map {
        case (buyPrice, sellPrice) =>
          getPotentialProfit(buyPrice = buyPrice, sellPrice = sellPrice)
      }
      .max
}

/** Return a Some(profit) if there is a potential profit here - else return a None **/
def getPotentialProfit(buyPrice: Int, sellPrice: Int): Option[Int] =
  if (sellPrice > buyPrice) Some(sellPrice - buyPrice)
  else None

/** Test cases **/
checkSolution(
  stockPrices = List(163, 112, 105, 100, 151),
  maximumProfit = Some(51)
)
checkSolution(stockPrices = List(1), maximumProfit = None)
checkSolution(stockPrices = List(1, 2), maximumProfit = Some(1))
checkSolution(stockPrices = List(2, 1), maximumProfit = None)

def checkSolution(stockPrices: List[Int], maximumProfit: Option[Int]): Unit = {
  val result = findMaximumProfit(stockPrices.toArray)

  assert(
    maximumProfit == result,
    s"For input ${stockPrices}, got result ${result}; expected $maximumProfit"
  )
}

Explanation

We will derive the solution mathematically, so that we are certain that we are right (I will not even name the algorithm in this explanation because the mathematics is quite important so you can derive the solution for variations of this problem - knowing the algorithm is mostly not enough).

Our final goal is to find out \(\$_{\max} = \max\{\$_1, \$_2, ..., \$_{n-1}\}\), where \(\$_d\) is the maximum profit that that can be gained by can be achieved at buying a stock on day \(d\) at price \(p_d\) and selling it any day after \(d\). \(n-1\) is because cannot buy-and-sell on the same day.

The price at which we sell stock after day \(d\) is simply the maximum price after day \(d\) (as to maximise the profit). If we name that \(S_d\) then it will be \(S_d = \max\{p_{d+1}, p_{d+2}, ..., p_{n}\}\). Then, \(\$_d = S_d - p_d\).

Notice that \(\max\{a, b, c\} = \max\{\max\{a, b\}, c\}\) (this is very important in this sort of problems), meaning that \(S_d = \max\{p_{d+1},S_{d+1}\}\).

Computing \(\$_{max} = \max\{S_1-p_1,S_2-p_2, ..., S_{n-1} - p_{n-1}\}\) directly is \(O(n^2)\) but because of our earlier relation, we can pre-compute the value of \(S_d\) from the value of \(S_{d+1}\) - it just means we have compute from right to left - in fact we can compute the whole array of \(S\) like that.

After computing \(S_d\), we already have \(p_d\) from the original price array, and then we can compute \(\$_d\) from all pairings of \(S_d\) and \(p_d\) to eventually find \(\$_{max}\).

In Scala, however, we needn't iterate and mutate - we can utilise functional programming and Scala's powerful collections:

To "iterate" left-to-right, and collect results, use `scanLeft`:
List(1, 2, 3, 4, 5).scanLeft(0)(_ + _)
// List(0, 1, 3, 6, 10, 15): List[Int]
To "iterate" right-to-left, and collect results, use `scanRight`:
List(1, 2, 3, 4, 5).scanRight(0)(_ + _)
// List(15, 14, 12, 9, 5, 0): List[Int]
To "iterate" across pairings of two Arrays, use `zip`:
List(1, 2, 3, 4).zip(List(5, 6, 7, 8, 9))
// List((1,5), (2,6), (3,7), (4,8)): List[(Int, Int)]

We plug in the relation for \(S_d\) into a `scanRight`, then we `zip` the prices \(p_d\) with \(S_d\) to find maximum potential profit at day \(d\), and then we find the maximum value across all values of \(d\).

How can you do `.max` on a `Array[Option[Int]]`?!!!

Scala is powerful. It has something called an `Ordering` which is automatically generated for eg `Option` so long as there is an `Ordering` for an `Int`.