Largest in Array

easy

Given an array arr of integers, find and return the largest element in it.

The array always has at least one element, so an answer is guaranteed to exist. Values may repeat — if the maximum appears more than once, you still return that single value.

Hints

You only care about one value — the biggest. Do you actually need the array in any particular order to find it?
Keep a single 'best so far' and update it as you walk the array from left to right.
Initialize your running maximum to the first element, then compare every other element against it in one pass.

Common doubts

Return the value itself. arr = [5, 5, 5, 5] returns 5 — duplicates of the maximum don't change the answer.
Seeding with arr[0] is always a real element, so the answer is correct even for arrays of all zeros or (in the general case) all negatives. Seeding with 0 would silently break on negative inputs.

Interview follow-ups

Track two running values, largest and secondLargest, updating both in a single pass — and be careful to push the old largest down into secondLargest when a new champion appears.
Use a min-heap of size k for an O(n log k) scan, or Quickselect to partition around the k-th order statistic in O(n) average time.

Fun facts

  • Finding the max needs exactly n-1 comparisons in the worst case — think of a knockout tournament: each game eliminates one loser, and n-1 losers must be eliminated to leave one winner.
  • This same running-best pattern powers max() built-ins, streaming analytics, and the reduce/fold operation in functional programming.

Asked at

AmazonGoogleMicrosoftAdobe
Frequently Sometimes Occasionally
Example 1
Input: arr = [1, 8, 7, 56, 90]
Output: 90
The largest element of the array is 90.
Example 2
Input: arr = [5, 5, 5, 5]
Output: 5
Every element is 5, so the largest is 5.
Example 3
Input: arr = [10]
Output: 10
A single element is trivially the largest.
Constraints

- 1 <= arr.size <= 10^6 - 0 <= arr[i] <= 10^6

Solve this problem →