878367. Maximum Element in Array
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:
- Initialize
max_elementto the first element in the array. - Iterate through the rest of the array.
- For each element, compare it with
max_element. - If the current element is greater than
max_element, updatemax_element. - 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
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));
}
}