Explorer
Data Structures & Algorithms

Find the largest element in an array by keeping track of the maximum value seen so far.

Problem Statement

Given an array of integers, find the largest element in the array.

Examples

Input: arr = [1, 8, 7, 56, 90]

Output: 90

Explanation: 90 is the largest element in the array.

Constraints

Standard constraints

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: Think about maintaining a variable to track the maximum element seen so far. šŸ’” Hint 2: Initialize your max variable with the first element arr[0] and iterate from index 1 to the end. šŸ’” Hint 3: Compare each element with max. If the current element is greater, update max. Returns max at the end.

Editorial & Approach

Problem Overview & Intuition

To find the maximum element in an unsorted array, we must examine every element at least once. Sorting the array takes O(N log N), but a single linear scan keeps track of the maximum value encountered so far in optimal O(N) time.

Step-by-Step Approach

  1. Initialize a variable max with the first element of the array: let max = arr[0];.
  2. Iterate through the array from index 1 to arr.length - 1.
  3. At each step, if arr[i] > max, update max = arr[i].
  4. After completing the loop, return max.

Optimal Implementation (JavaScript)

function largestElement(arr) {
  if (arr.length === 0) return -1;
  let max = arr[0];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] > max) {
      max = arr[i];
    }
  }
  return max;
}

Complexity Analysis

Time Complexity O(N) — single pass through the array.
Space Complexity O(1) — constant extra memory used.

Edge Cases & Corner Traps Handled

  • Single element array: immediately returns arr[0].
  • All negative values: correctly returns the least negative number.
  • All identical values: correctly returns that value.

Largest Element in an Array

Easy
Given an array of integers, find the largest element in the array.
Example Scenarios
1Example 1
Input: arr = [1, 8, 7, 56, 90]
Output: 90
Explanation:

90 is the largest element in the array.

Constraints
•Standard constraints
Editor
Loading Editor...
arr =
[1, 8, 7, 56, 90]
Output:Click "Run" above to execute and verify your code here.
90