Largest Element
EasyOne pass, keep the best so far
Problem
Given an array of integers nums, return the value of the largest element in the array
Walk the list once, always remembering the biggest number you have seen.
The idea
Seed the answer with the first element and replace it whenever a later element is bigger. Seeding with the first element rather than zero is what makes it correct for all-negative arrays.
The trick
- Never initialise to 0 — start from nums[0] or negative infinity.
- O(n) with a single comparison per element; you cannot do better without extra structure.
i
3
8
1
9
4
0
1
2
3
4
max3
Step 1 of 6. Start: take the first element 3 as the max so far. Values: 3, 8, 1, 9, 4. Pointers: i at index 0. max 3.
1/6
Optimal
timeO(n)spaceO(1)
1max = nums[0]2for x in nums:3 if x > max: max = x4return maxInput
- array
- [3, 8, 1, 9, 4]
Memory
- i
- = 0 [3]
Output
- max
- 3
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- nums = [3, 3, 6, 1]
- Output:
- 6
- Explanation:
- 6 is the biggest value in the list.
Example 2
- Input:
- nums = [3, 3, 0, 99, -40]
- Output:
- 99
- Explanation:
- 99 towers over the rest.
Example 3
- Input:
- nums = [-5, -2, -9]
- Output:
- -2
- Explanation:
- Even with all negatives, -2 is the largest.
Constraints
- 1 <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
- nums may contain duplicate elements.
Practice this problem:GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.