Start learning free

LESSON 148 OF 415 · LOOPS & GLOBAL VARIABLES

Max in Array in Swift: Finding the Maximum with a Loop

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 max(), it would defy the purpose of the challenge. Write the whole code yourself.

STEP 1 OF 4
    Ctrl + Enter to check

    SWIFT · LOOPS & GLOBAL VARIABLES

    Max In Array in Swift, explained

    Problem overview

    The method maxInArray receives an array of integers and returns the largest value in it. For nums = [2, 7, 11, 8, 11, 8, 3, 11] the answer is 11. A value can appear more than once, as 11 does here, and the answer is still that value.

    The task asks you to find the maximum with a loop of your own instead of calling a method on the array that does it for you.

    Approach: keep the best value seen so far

    Walk through the array once and remember the largest element met so far. When a bigger one appears, it replaces the remembered value. After the last element, the remembered value is the maximum of the whole array, because every element was compared against it.

    The only question is where to start. Starting from 0 is a trap: in an array of negative numbers such as [-5, -2, -9], 0 is bigger than every element, so it would never be replaced and the function would return a number that isn't in the array. Starting from the first element avoids that, since the starting value is always a real member of the array.

    Step by step

    1. Start from the first element. var maxVal = nums[0]. It is a var because it may be replaced as the loop runs.
    2. Loop over the values. for val in nums visits each element in order. The first pass compares the first element with itself, which does no harm.
    3. Keep the larger one. maxVal = max(maxVal, val) picks whichever of the two is bigger, so maxVal never decreases.
    4. Return maxVal after the loop.

    The solution in Swift

    class Solution {
        func maxInArray(_ nums: [Int]) -> Int {
            var maxVal = nums[0]
            for val in nums {
                maxVal = max(maxVal, val)
            }
            return maxVal
        }
    }
    

    Swift details worth knowing:

    • The global max function. max(a, b) compares two values and returns the larger. It is a small helper for two values, not the array's own maximum method, so the loop is still doing the searching. An if val > maxVal { maxVal = val } would do the same job with no helper.
    • Indexing an empty array crashes. nums[0] on an empty array stops the program with an index-out-of-range error. The function assumes the input has at least one element. If empty input had to be handled, the return type would need to be optional, Int?, so that the function could return nil.
    • Naming. A local called maxVal keeps the name max free for the function. A variable named max would hide the function inside the method, and the call max(maxVal, val) would no longer compile.
    • Integer limits. No arithmetic happens, only comparisons, so there is no overflow to worry about.

    Complexity

    Time: O(n) for n elements. The loop compares each element once, and each comparison takes constant time.

    Space: O(1). The function keeps one variable for the best value and one for the loop.

    Edge cases and common mistakes

    • All negative numbers. [-5, -2, -9] returns -2. Starting at 0 would wrongly return 0.
    • One element. [4] returns 4.
    • Repeated maximum. Repeats are harmless: max keeps the same value.
    • Returning inside the loop. That would give the first element at best, since the function would end on the first pass.
    • Empty array. This crashes at nums[0], as described above.

    Testing

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