Largest Element in Array
Problem​
Given an array A[] of size n. The task is to find the largest element in it.
Examples:​
Example 1:
Input:
n = 5
A[] = {1, 8, 7, 56, 90}
Output:
90
Explanation:
The largest element of given array is 90.
Example 2:
Input:
n = 7
A[] = {1, 2, 0, 3, 2, 4, 5}
Output:
5
Explanation:
The largest element of given array is 5.
Your task:​
You don't need to read input or print anything. Your task is to complete the function largest() which takes the array A[] and its size n as inputs and returns the maximum element in the array
- Expected Time Complexity:
- Expected Auxiliary Space:
Constraints:​
Array may contain duplicate elements.
Solution​
Python​
def largest( arr, n):
mx = arr[0]
for i in range(1, n):
if arr[i] > mx:
mx = arr[i]
return mx
Java​
public int largest(int arr[], int n) {
int mx = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > mx) {
mx = arr[i];
}
}
return mx;
}
C++​
public:
int largest(vector<int> &arr, int n) {
int mx = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > mx) {
mx = arr[i];
}
}
return mx;
}
};
C​
int largest(int arr[], int n) {
int mx = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > mx) {
mx = arr[i];
}
}
return mx;
}
- Time Complexity:
- Auxiliary Space: