Coding problem · Easy · Basics

Find the Maximum

Easy Algorithms & data structures

Return the largest number in the non-empty array nums. Try it without built-in max functions first.

Example 1

Input: nums = [3,9,2,7]
Output: 9

Example 2

Input: nums = [-4,-2,-8]
Output: -2

Hints

Hint 1

Start with the first element as the best so far, then compare each other element with it.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(1)

Assume the first element is the maximum, then replace it whenever a bigger element appears. Starting from 0 would be wrong for all-negative arrays.

Reference solution

function findMax(nums) {
  let best = nums[0];
  for (const n of nums) if (n > best) best = n;
  return best;
}

Was this page helpful?