Largest Element in an Array
Problem Statement
Given an array arr[], the task is to find and return the largest element in the array.
Example 1:
Input: arr[] = [1, 8, 7, 56, 90]
Output: 90
Explanation: The largest element in the array is 90.
Example 2:
Input: arr[] = [5, 5, 5, 5]
Output: 5
Explanation: All elements are equal, so the largest element is 5.
Get Priyanka’s stories in your inbox
Join Medium for free to get updates from this writer.
Problem statement: Largest in Array | Practice | GeeksforGeeks
Approach
We can solve this problem by traversing the array and keeping track of the largest element found so far.
- Initialize a variable
largestwithInteger.MIN_VALUE. This ensures that even if all array elements are negative, the algorithm works correctly. - Traverse the array using a
forloop. - For each element, compare it with the current value of
largestusing thegetMax()method. - Update
largestwith the greater value. - After traversing the entire array, return
largest.
Java Solution
class Solution {
public static int getMax(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
public static int findLargest(int[] arr) {
int largest = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
largest = getMax(arr[i], largest);
}
return largest;
}
public static int largest(int[] arr) {
return findLargest(arr);
}
}Dry Run
Consider the input array:
arr[] = [1, 8, 7, 56, 90]
Initially, largest = Integer.MIN_VALUE.
ElementCurrent Largest11887856569090
After processing all the elements, the value of largest is 90, which is returned as the answer.
Complexity Analysis
Time Complexity: O(n)
The algorithm traverses the array exactly once, where n is the number of elements in the array. Each comparison takes constant time.
Space Complexity: O(1)
The algorithm uses only a constant amount of extra space for variables such as largest and i.
Conclusion
The largest element in an array can be found efficiently by traversing the array once and maintaining the maximum value encountered so far. The solution takes O(n) time and O(1) extra space, making it optimal for this problem.






