878367. Maximum Element in Array

Basic

Maximum Element in Array

Slug: largest-element-in-array4009--142158

Difficulty: Basic

Id: 878367

Topic Tags: Arrays, Data Structures

Company Tags: Infosys, Oracle, Wipro, Morgan Stanley

Summary

The problem is to find the maximum element in an array. The array can contain any type of elements, and it's not necessary that all elements are distinct. This problem involves basic concepts of arrays and data structures.

Detailed Explanation

To solve this problem, we will iterate through the entire array and keep track of the maximum element encountered so far. We will start by initializing a variable max_element to the first element in the array. Then, we will iterate through the rest of the array, comparing each element with max_element. If an element is greater than max_element, we update max_element.

Here's the step-by-step breakdown:

  1. Initialize max_element to the first element in the array.
  2. Iterate through the rest of the array.
  3. For each element, compare it with max_element.
  4. If the current element is greater than max_element, update max_element.
  5. Return max_element.

The time complexity for this solution is O(n), where n is the number of elements in the array. This is because we are iterating through the entire array once.

The space complexity is O(1), as we are not using any extra space that scales with the input size.

Here's a simple ASCII art diagram illustrating the array:

1 2 3 4 5

Optimized Solutions

Java

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

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        System.out.println("Maximum element is " + maxElement(arr));
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.