Read the problem before touching the keyboard
Most failed coding rounds fail in the first two minutes: the candidate starts typing a solution to a problem they have not fully read. Slow down and write these five things down (in a comment, on the whiteboard, or out loud) before any code.
- 1Restate it
One sentence, in your own words. "Given a list of prices, return the biggest profit from one buy followed by one later sell."
- 2Inputs and outputs, with types
prices: Seq[Int]in,Intout. Can the sequence be empty? What is returned then? Should "no answer" be anOption? - 3Constraints
How big is n? Can values be negative? Duplicates? Already sorted? These decide the algorithm (see the Big-O lesson below).
- 4Two examples by hand
One normal, one tricky. Work them out on paper. If you cannot do it by hand, you cannot code it.
- 5Edge cases
Empty input, one element, all equal, already sorted, values big enough to overflow
Int(Scala wraps silently, like Java; useLongorBigInt, see Module 01).
// Restated: best profit from one buy then one later sell; 0 if prices only fall.
// Input: prices (may be empty). Output: Int >= 0.
def maxProfit(prices: Seq[Int]): Int =
prices.foldLeft((Int.MaxValue, 0)) { case ((lowest, best), price) =>
(lowest min price, best max (price - (lowest min price)))
}._2
@main def run(): Unit =
println(maxProfit(Seq(7, 1, 5, 3, 6, 4))) // normal: buy at 1, sell at 6
println(maxProfit(Seq(7, 6, 4, 3, 1))) // prices only fall
println(maxProfit(Seq.empty)) // empty
println(maxProfit(Seq(5))) // one day5
0
0
0The fold carries two values, the cheapest buy so far and the best profit so far, in a tuple. The four calls are the examples and edge cases from the reading step, written before the function body, not bolted on after.
Change the contract to "return Option[(Int, Int)]: the buy day and sell day, or None if no profit is possible". Which of the four calls now needs a different expected answer?
