Problem overview
The lesson has two methods in one class. maxOfTwo(a, b) is a helper that returns the larger of two integers. maxOfThree(a, b, c) returns the largest of three integers, and it must get its answer by calling the helper instead of comparing numbers itself. Built-in max functions are off limits.
For 3, 7, 5 the answer is 7. For -3, -8, -1 it is -1, the negative number closest to zero. For 4, 4, 2 it is 4: when two numbers tie, either one is the answer because the value is the same.
Approach: build the answer from a smaller one
Finding the larger of two numbers is easy. Finding the largest of three reduces to that: take the larger of the first two, then the larger of that winner and the third. The largest of all three can't lose either match.
Splitting the work this way keeps each method small. The comparison is written once, in maxOfTwo, and maxOfThree only combines calls. The same pattern extends to four numbers or more without any new comparing code.
Step by step
- In
maxOfTwo, returnawhen it is greater thanb.returnends the method immediately, so nothing below runs in that case. - Return
bbelow theif. This line is reached only whenais not greater thanb. Eitherbis larger, or they are equal andbis just as good. Noelseis needed. - In
maxOfThree, nest the calls. The inner callmaxOfTwo(a, b)runs first, and its result becomes the first argument of the outer call, which compares it withc. A method calls another method of the same class by name, with no object in front.
The solution in Scala
class Solution {
def maxOfTwo(a: Int, b: Int): Int = {
if (a > b) {
return a
}
return b
}
def maxOfThree(a: Int, b: Int, c: Int): Int = {
return maxOfTwo(maxOfTwo(a, b), c)
}
}
Scala details worth knowing:
- Declared return types. A method that uses
returnmust state its result type, here: Int, after the parameter list. - Same parameter names, separate variables. Both methods have parameters called
aandb. Each method has its own variables, so the callmaxOfTwo(a, b)just hands over the current values. ifis an expression. Scala could write the helper asif (a > b) a else b, which is the value of the method with noreturnat all. The lesson uses the early-return form, which is the one most beginners know from other languages.
Edge cases and common mistakes
- Ties. With
maxOfTwo(5, 5)the conditiona > bis false, so the helper returnsb, which is 5. The answer is right because both values are equal. - Negative numbers. Nothing special happens:
-1 > -8is true. Starting a "largest so far" at 0 would be the real bug, because it would return 0 for all-negative input. - Comparing in
maxOfThree. Adding your ownifthere defeats the point of the lesson. All comparing lives in the helper. - Calling the helper with the wrong values.
maxOfTwo(a, c)alone would ignoreb. The nested call must pass the winner of the first match.
Testing
maxOfThree(3, 7, 5)gives7.maxOfThree(-3, -8, -1)gives-1.maxOfThree(4, 4, 2)gives4.maxOfThree(1, 2, 3)gives3.maxOfTwo(5, 5)gives5.
