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:
- Initialize a variable
max_elementto store the maximum element found so far. - Iterate through the input array using a for loop or similar construct.
- For each element in the array, check if it is greater than the current
max_element. - If the current element is larger, update
max_elementwith its value. - 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
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;
}