AlgoMaster Logo

Largest Element in an Array

Last Updated: June 7, 2026

easy
2 min read

Understanding the Problem

The comparison is trivial; correctness hinges on where the scan starts from.

The array can hold negative numbers, so you cannot assume the answer is positive or start tracking from zero. If you seed your running maximum with 0 and the array is [-5, -2, -9], your code returns 0, which is not even in the array. The largest value can repeat, but a maximum that appears twice is still the maximum.

You must look at every element at least once to be sure none is bigger, so a single pass is both necessary and enough. No sorting, no extra data structure.

Key Constraints:

  • -2^31 <= nums[i] <= 2^31 - 1 → Full 32-bit signed range. Values can be negative, so never seed the running maximum with 0. Seed it with nums[0], an actual element of the array.
  • 1 <= nums.length → The array is non-empty, so nums[0] always exists and is a safe starting value.
  • Duplicates allowed → The maximum can appear more than once. Using > to update the running maximum handles this correctly, since a tie leaves the existing maximum in place and the value is the same either way.

Approach 1: Linear Scan

Intuition

Keep a single variable, the running maximum, and walk the array once. Each time you meet a value larger than the current maximum, that value becomes the new maximum.

Seed the variable with nums[0] rather than 0. Because nums[0] is a real element, the running maximum is always a value that lives in the array, which keeps the logic correct even when every number is negative. Seeding with the first element also lets you scan from index 1 onward, since index 0 is already accounted for.

Algorithm

  1. Set largest = nums[0].
  2. Loop from index 1 to the end of the array.
  3. For each element nums[i], if nums[i] > largest, set largest = nums[i].
  4. After the loop, return largest.

Example Walkthrough

Input:

0
-5
1
-2
2
-9
nums

Start with largest = nums[0] = -5. Move to index 1, where nums[1] = -2. Since -2 > -5, update largest = -2. Move to index 2, where nums[2] = -9. Since -9 < -2, leave largest unchanged. The scan ends, and largest holds -2.

Note how seeding with -5 instead of 0 is what lets an all-negative array return the right answer.

-2
largest

Code