Scala algorithm: Find maximum potential profit from an array of stock price

Algorithm goal

Find the maximum potential profit given an array of stock prices, based on a buy followed by a sell. Where not possible 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)

Algorithm in Scala

22 lines of Scala (version 2.13), showing how concise Scala can be!

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 in Scala

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)

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. (this is © from www.scala-algorithms.com)

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

Scala concepts & Hints

  1. Drop, Take, dropRight, takeRight

    Scala's `drop` and `take` methods typically remove or select `n` items from a 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))
    
  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!

    assert(Option(1).flatMap(x => Option(x + 2)) == Option(3))
    
    assert(Option(1).flatMap(x => None) == None)
    
  3. 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")
    
  4. scanLeft and scanRight

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

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

    Stack safety is present where a function cannot crash due to overflowing the limit of number of recursive calls.

    This function will work for n = 5, but will not work for n = 2000 (crash with java.lang.StackOverflowError) - however there is a way to fix it :-)

    In Scala Algorithms, we try to write the algorithms in a stack-safe way, where possible, so that when you use the algorithms, they will not crash on large inputs. However, stack-safe implementations are often more complex, and in some cases, overly complex, for the task at hand.

    def sum(from: Int, until: Int): Int =
      if (from == until) until else from + sum(from + 1, until)
    
    def thisWillSucceed: Int = sum(1, 5)
    
    def thisWillFail: Int = sum(1, 300)
    
  6. View

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

  7. 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))
    
    assert(List(5, 6).zipAll(List('A'), 9, 'Z') == List(5 -> 'A', 6 -> 'Z'))
    
    assert(List(5).zipAll(List('A', 'B'), 1, 'Z') == List(5 -> 'A', 1 -> 'B'))
    

Scala Algorithms: The most comprehensive library of algorithms in standard pure-functional Scala

Think in Scala & master the highest paid programming language in the US

Scala is used at many places, such as AirBnB, Apple, Bank of America, BBC, Barclays, Capital One, Citibank, Coursera, eBay, JP Morgan, LinkedIn, Morgan Stanley, Netflix, Singapore Exchange, Twitter.

Study our 104 Scala Algorithms: 6 fully free, 59 published & 45 upcoming

Fully unit-tested, with explanations and relevant concepts; new algorithms published about once a week.

  1. Find minimum missing positive number in a sequence
  2. Longest increasing sub-sequence length
  3. Compute the length of longest valid parentheses
  4. Counting inversions of a sequence (array) using a Merge Sort
  5. Check if an array is a palindrome
  6. Monitor success rate of a process that may fail
  7. Find combinations adding up to N (non-unique)
  8. Remove duplicates from an unsorted List
  9. Find combinations adding up to N (unique)
  10. Find k closest elements to a value in a sorted Array
  11. Make a queue using stacks (Lists in Scala)
  12. Single-elimination tournament tree
  13. Quick Sort sorting algorithm in pure immutable Scala
  14. Compute a Roman numeral for an Integer, and vice-versa
  15. Matching parentheses algorithm with foldLeft and a state machine
  16. Traverse a tree Breadth-First, immutably
  17. Read a matrix as a spiral
  18. Remove duplicates from a sorted list (state machine)
  19. Merge Sort: stack-safe, tail-recursive, in pure immutable Scala, N-way
  20. Binary search a generic Array
  21. Merge Sort: in pure immutable Scala
  22. Make a queue using Maps
  23. Is an Array a permutation?
  24. Count number of contiguous countries by colors
  25. Add numbers without using addition (plus sign)
  26. Tic Tac Toe MinMax solve
  27. Run-length encoding (RLE) Encoder
  28. Print Alphabet Diamond
  29. Balanced parentheses algorithm with tail-call recursion optimisation
  30. Reverse a String's words efficiently
  31. Count number of changes (manipulations) needed to make an anagram with foldLeft and a MultiSet
  32. Compute nth row of Pascal's triangle
  33. Run-length encoding (RLE) Decoder
  34. Check if a number is a palindrome
  35. In a range of numbers, count the numbers divisible by a specific integer
  36. Find the index of a substring ('indexOf')
  37. Reshape a matrix
  38. Closest pair of coordinates in a 2D plane
  39. Find the contiguous slice with the minimum average
  40. Compute maximum sum of subarray (Kadane's algorithm)
  41. Binary search in a rotated sorted array
  42. Rotate Array right in pure-functional Scala - using an unusual immutable efficient approach
  43. Length of the longest common substring
  44. Tic Tac Toe board check
  45. Find an unpaired number in an array
  46. Check if a String is a palindrome
  47. Count binary gap size of a number using tail recursion
  48. Remove duplicates from a sorted list (Sliding)
  49. Find sub-array with the maximum sum
  50. Find the minimum absolute difference of two partitions
  51. Find maximum potential profit from an array of stock price
  52. Fibonacci in purely functional immutable Scala
  53. Fizz Buzz in purely functional immutable Scala
  54. Count factors/divisors of an integer
  55. Compute single-digit sum of digits
  56. Traverse a tree Depth-First
  57. Reverse bits of an integer
  58. QuickSelect Selection Algorithm (kth smallest item/order statistic)
  59. Rotate a matrix by 90 degrees clockwise

Explore the 21 most useful Scala concepts

To save you going through various tutorials, we cherry-picked the most useful Scala concepts in a consistent form.

  1. Class Inside Class
  2. Class Inside Def
  3. Collect
  4. Def Inside Def
  5. Drop, Take, dropRight, takeRight
  6. foldLeft and foldRight
  7. For-comprehension
  8. Lazy List
  9. Option Type
  10. Ordering
  11. Partial Function
  12. Pattern Matching
  13. Range
  14. scanLeft and scanRight
  15. Sliding / Sliding Window
  16. Stack Safety
  17. State machine
  18. Tail Recursion
  19. Type Class
  20. View
  21. Zip

Register now (free)