Find maximum potential profit from an array of stock prices - pure-functional immutable Scala solution

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:

  • On Codility: MaxProfit - Given a log of stock prices compute the maximum possible earning. (100% pass)

Solution

def findMaximumProfit(stockPrices: Array[Int]): Option[Int] = {
  val maximumSellPricesFromIonward = stockPrices.view
    .scanRight(0)({
      case (maximumPriceSoFar, dayPrice) =>
        Math.max(maximumPriceSoFar, dayPrice)
    })
    .toArray
  val maximumSellPricesAfterI = maximumSellPricesFromIonward.drop(1)
  if (stockPrices.length < 2) None
  else
    stockPrices
      .zip(maximumSellPricesAfterI)
      .map({
        case (buyPrice, sellPrice) =>
          getPotentialProfit(buyPrice = buyPrice, sellPrice = sellPrice)
      })
      .max
}

def getPotentialProfit(buyPrice: Int, sellPrice: Int): Option[Int] = {
  if (sellPrice > buyPrice) Some(sellPrice - buyPrice) else None
}

Test cases

assert(findMaximumProfit(Array(163, 112, 105, 100, 151)).contains(51))
assert(findMaximumProfit(Array(1)).isEmpty)
assert(findMaximumProfit(Array(1, 2)).contains(1))
assert(findMaximumProfit(Array(2, 1)).isEmpty)

Scala Concepts

Drop, Take, dropRight, takeRight

Scala's `drop` and `take` methods typically remove or select `n` items from a collection.

This allows for quick and easy collection manipulations.

The versions with `Right` act on the right side of the collection.

assert(List(1, 2, 3).drop(2) == List(3))

assert(List(1, 2, 3).take(2) == List(1, 2))

assert(List(1, 2, 3).dropRight(2) == List(1))

assert(List(1, 2, 3).takeRight(2) == List(2, 3))

assert((1 to 5).take(2) == (1 to 2))
Option Type

The 'Option' type is used to describe a computation that either has a result or does not. In Scala, you can 'chain' Option processing, combine with lists and other data structures. For example, you can also turn a pattern-match into a function that return an Option, and vice-versa!

Some examples:

final case class Page(title: String, mainCategory: Option[String])

val pages = List(
  Page(title = "Tail Recursion", mainCategory = None /** No category **/ ),
  Page(title = "Option", mainCategory = Some("standard library")),
  Page(title = "zip", mainCategory = Some("standard library"))
)

val categories: Set[String] = pages.flatMap(_.mainCategory).toSet

assert(categories == Set("standard library"))

def pageCategory(title: String): Option[String] = {
  for {
    page <- pages.find(_.title == title)
    category <- page.mainCategory
  } yield category
}

def pageCategory2(title: String): Option[String] =
  pages.find(_.title == title).flatMap(_.mainCategory)

def pageCategory3(title: String): Option[String] =
  pages.collectFirst {
    case Page(`title`, mainCategory) => mainCategory
  }.flatten

assert(pageCategory("zip").contains("standard library"))

assert(pageCategory("zip") == Some("standard library"))

assert(pageCategory("zip") == Some("standard library"))

assert(pageCategory2("zip") == pageCategory("zip"))

assert(pageCategory3("zip") == pageCategory("zip"))

assert(List[String]("X").headOption == Some("X"))

assert(List[String]().headOption.isEmpty)

val startWithT: String = Option("Some test") match {
  case Some(value) if value.startsWith("T") => value
  case Some(value)                          => s"T${value}"
  case None                                 => "T"
}

assert(startWithT == "TSome test")
Pattern Matching

Pattern matching in Scala lets you quickly identify what you are looking for in a data, and also extract it.

assert("Hello World".collect {
  case character if Character.isUpperCase(character) => character.toLower
} == "hw")

assert("Hello World".filter(Character.isUpperCase).map(_.toLower) == "hw")

assert((1 to 10).collect {
  case num if num % 3 == 0 => "Fizz"
  case num if num % 5 == 0 => "Buzz"
}.toList == List("Fizz", "Buzz", "Fizz", "Fizz", "Buzz"))

Pattern matching is used by methods like Collect, but can also be easily integrated into normal functions.

Pattern matches are effectively "Partial Functions", of type PartialFunction[Input, Output] which is isomorphic to Input => Option[Output]. See Option Type.

scanLeft and scanRight

Scala's `scan` functions enable you to do folds like foldLeft and foldRight, while collecting the intermediate results

This is incredibly useful when you need to collect a sequence of states, such as in MaximumSubArraySum.

Example

assert(List(1, 2, 3, 4, 5).scanLeft(0)(_ + _) == List(0, 1, 3, 6, 10, 15))

assert(List(1, 2, 3, 4, 5).scanRight(0)(_ + _) == List(15, 14, 12, 9, 5, 0))

assert(
  Iterator.from(1).scanLeft(0)(_ + _).take(5).toList == List(0, 1, 3, 6, 10)
)
View

The .view syntax creates a structure that mirrors another structure, until "forced" by an eager operation like .toList, .foreach, .forall, .count.

In the example below, we can see the view in action:

var counted = 0

val resultingList = List(1, 2, 3, 4).view
  .map { num =>
    counted = counted + 1
    num + 1
  }
  .take(2)
  .toList

assert(resultingList == List(2, 3))

assert(counted == 2)

If we add a side-effect inside a map (don't do this normally!), We note that items 3 and 4 are never touched/evaluated, meaning we perform a "lazy" computation.

This is very similar to an Iterator, except views can be Indexed, and also reversed, which is a tremendously useful fact when dealing with arrays, for example when you want to zip two arrays together, such as in CheckArrayIsAPalindrome

On views, you can perform almost any typical collection operation, such as `maxBy`, `count`, `flatMap` and so forth.

And you can get views from almost any data type. Benefits other than lazy computation include potentially fusing of operations by the Java compiler, because instead of creating a new list for every stage, you evaluate new items one-by-one, meaning that if there are any optimisations to be made per one-item basis, you may get a performance boost.

Zip

'zip' allows you to combine two lists pair-wise (meaning turn a pair of lists, into a list of pairs)

It can be used over Arrays, Lists, Views, Iterators and other collections.

assert(List(1, 2, 3).zip(List(5, 6, 7)) == List(1 -> 5, 2 -> 6, 3 -> 7))

assert(List(1, 2).zip(List(5, 6, 7)) == List(1 -> 5, 2 -> 6))

assert(List(5, 6).zipWithIndex == List(5 -> 0, 6 -> 1))

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. Please see the 'Scala concepts' below.

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`.