Start learning free

LESSON 143 OF 348 · LOOPS & GLOBAL VARIABLES

Maximum in an Array in Kotlin: One Pass with maxOf

Practice Read the full explanation

Given an array of integers, return the maximum value from the array.

Example:

Input: nums = [2, 7, 11, 8, 11, 8, 3, 11]
Output: 11
Explanation: The maximum value is 11

Note:

Do not use builtin functions such as maxOf(), it would defy the purpose of the challenge. Write the whole code yourself.

STEP 1 OF 4
    Ctrl + Enter to check

    KOTLIN · LOOPS & GLOBAL VARIABLES

    Max In Array in Kotlin, explained

    Problem overview

    The function maxInArray receives an IntArray named nums and returns its largest value. The array can contain repeated values and negative numbers.

    In the example, nums = [2, 7, 11, 8, 11, 8, 3, 11]. The largest value is 11, which appears three times, and the function returns 11 once, as a value rather than a count or a position.

    Approach: keep the best value seen so far

    To find the biggest element, you have to look at every element at least once, because any unseen one could be larger. The usual technique is a running maximum. Hold the largest value seen so far, then walk through the array and replace it whenever something bigger shows up. After the last element, the variable holds the answer.

    The one decision is where the running maximum starts. A tempting choice is 0, but it breaks for arrays that contain only negative numbers: for [-5, -2, -9] a start of 0 would never be beaten, and the function would return 0, which isn't even in the array. Starting with the first element is always safe, because the maximum of the whole array is at least as large as its first element.

    Step by step

    1. Initialize the maximum with var maxVal = nums[0]. It is a var because it can be replaced during the loop.
    2. Loop over the values with for (num in nums). No index is needed, because only the values matter.
    3. Update the maximum with maxVal = maxOf(maxVal, num). The standard function maxOf(a, b) returns the larger of its two arguments, so maxVal never decreases and always holds the largest value seen so far.
    4. Return maxVal after the loop.

    The solution in Kotlin

    class Solution {
        fun maxInArray(nums: IntArray): Int {
            var maxVal = nums[0]
            for (num in nums) {
                maxVal = maxOf(maxVal, num)
            }
            return maxVal
        }
    }
    

    The Kotlin details behind it:

    • maxOf compares two values. It is a top-level function in the standard library and needs no import. It is not the same as taking the maximum of a whole array: nums.max() does that, and it is the kind of built-in the lesson's note asks you to avoid when writing the search by hand. Here maxOf is used only as the comparison inside your own loop. An if (num > maxVal) { maxVal = num } does the same job.
    • The first element is compared with itself. The loop starts at index 0, so the first pass computes maxOf(nums[0], nums[0]). That is harmless. You could skip it with for (i in 1 until nums.size), but the simpler loop is fine.
    • An empty array fails. nums[0] on an empty IntArray throws an ArrayIndexOutOfBoundsException with the message Index 0 out of bounds for length 0. A maximum of nothing has no sensible value, so the solution assumes the array has at least one element.
    • The type is Int. The smallest value an Int can hold is -2147483648. An array of nothing but that value correctly returns it, which would not work with a start value of 0 or with a made-up "minus infinity" constant that is too small.

    Complexity

    Let n be the length of nums.

    Time: O(n). The loop visits each element once and does a constant amount of work per element.

    Space: O(1). The function stores maxVal and the loop variable only.

    Edge cases and common mistakes

    • All negative numbers. [-5, -2, -9] returns -2. Initializing maxVal with 0 would return 0 instead.
    • A single element. [4] returns 4.
    • Repeated maxima. The maximum 11 in the example appears three times. The result is the same however many times it appears.
    • Returning inside the loop. The function would give up after the first element.
    • Declaring the maximum inside the loop. It would be reset on every pass, and the result would depend only on the last element.
    • Empty input. It throws, as described above.

    Testing

    • [2, 7, 11, 8, 11, 8, 3, 11] gives 11.
    • [-5, -2, -9] gives -2.
    • [4] gives 4.
    • [1, 2, 3, 4, 5] gives 5, with the maximum last.
    • [9, 3, 1] gives 9, with the maximum first.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free