703297. Largest Element in Array

Basic

Largest Element in Array

Slug: largest-element-in-array4009

Difficulty: Basic

Id: 703297

Topic Tags: Arrays, Data Structures

Company Tags: Infosys, Oracle, Wipro, Morgan Stanley

Summary

Find the maximum element in a given array. The input array contains integers and you need to find the largest integer present in it.

Detailed Explanation

To solve this problem, we can use a simple algorithm that iterates through the array once. We keep track of the maximum value seen so far and update it whenever we encounter a larger number. This approach has a time complexity of O(n), where n is the size of the input array, as we only need to traverse the array once.

Here's a step-by-step breakdown of the solution:

  1. Initialize a variable max_element to store the maximum element found so far.
  2. Iterate through the input array using a for loop or similar construct.
  3. For each element in the array, check if it is greater than the current max_element.
  4. If the current element is larger, update max_element with its value.
  5. After iterating through the entire array, return the maximum element found.

Here's an ASCII art diagram to illustrate this approach:

  +-----+
  | 1  |
  +-----+
  | 2  |
  +-----+
  | 3  |
  +-----+
  | ... |
  +-----+
  | max |
  +-----+

Time complexity: O(n) Space complexity: O(1)

Optimized Solutions

Java

View on GeeksforGeeks
public int largestElement(int[] arr) {
    int max = arr[0];
    for (int i = 1; i < arr.length; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.