Find Largest Element in an Array

Solve this Problem
Easy5–10 min
Topics
Companies
Practice:GFG ↗
Given an array of integers nums, find and return the largest element in the array. You may assume the array contains at least one element. Solve it with a single passSingle PassVisiting each element of the array exactly once, without sorting or scanning the array more than one time. through the array — no sorting required.

Test Case 1:

Input:nums = [3, 7, 2, 9, 4]
Output:9
Explanation:9 is greater than every other element in the array.

Test Case 2:

Input:nums = [1, 1, 1]
Output:1
Explanation:All elements are equal — that value is the largest.

Test Case 3:

Input:nums = [-5, -2, -9, -1]
Output:-1
Explanation:Even with all negatives, the largest is simply the greatest value present.

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹
🚀

Try the Dry Run

Don't just read the solution — watch it execute, one step at a time.

🧪Try your own test case
1class Solution {
2 public int findLargest(int[] nums) {
3 int largest = nums[0];
4 for (int i = 1; i < nums.length; i++) {
5 if (nums[i] > largest) {
6 largest = nums[i];
7 }
8 }
9 return largest;
10 }
11}
12
3
7
2
9
4
0
1
2
3
4
largest
Variables
largest3
INITIALIZE

Start by assuming the first element, nums[0] = 3, is the largest so far. We'll check every remaining element against it.

Step 1 / 12

Approach & Solutions

Brute Force — Sorting

Brute

Sort a copy of the array in ascending order. Once sorted, the largest element is guaranteed to be the very last one. Correct, but sorting does far more work than this problem actually needs.

TimeO(n log n)
SpaceO(n)
1class Solution { 2 public int findLargest(int[] nums) { 3 int[] sorted = nums.clone(); 4 Arrays.sort(sorted); 5 return sorted[sorted.length - 1]; 6 } 7}

Optimal — Single Pass

Optimal

Start by assuming the first element is the largest. Walk through the rest of the array once, and whenever you find a bigger element, update your running maximum. One pass, no extra memory, no sorting.

TimeO(n)
SpaceO(1)
1class Solution { 2 public int findLargest(int[] nums) { 3 int largest = nums[0]; 4 for (int i = 1; i < nums.length; i++) { 5 if (nums[i] > largest) { 6 largest = nums[i]; 7 } 8 } 9 return largest; 10 } 11}

Related Problems