Warm Up · Loops 02
Find Largest Number in an Array
Problem Statement
Write a function that returns the largest number in an array.
Example
Input: arr = [2, -6, 4, 8, 1, -9]
Process: largest goes 2 → 4 → 8
Output: 8
Approach
- Initialize a variable
largestto-Infinity. - Loop through the array.
- If the current element is greater than
largest, updatelargest. - Return
largestafter the loop ends.
Time & Space Complexity
Time Complexity: O(n) - where n is the number of elements in the array.
Space Complexity: O(1) - only a single variable is used.
Visualisation
1Start with the array
[2, -6, 4, 8, 1, -9]2Assume nothing is larger yet
let largest = -Infinity;3Larger than current largest? Replace it
arr[i] > largest4Largest number
8Explanation
- Starting at
-Infinityguarantees the first element always becomes the newlargest, even if every number is negative. - Each time a bigger value appears,
largestis updated: 2, then 4, then 8. - After one pass through the array,
largestholds the maximum value.
Your solution
Solve it in JavaScript and print the answer with console.log(). Run to see your output, then Submit to check it against the test cases.
// Write your solution in JavaScript // Print the answer with console.log()
Console
No output yet. Use console.log() to print values here.
Write your own solution and press Submit once to unlock the answer.