Practice › Arrays
Maximum in an Array
Easy · Arrays · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
Given an array of n integers, print the largest element.
Input
- First line:
n - Second line:
nspace-separated integers
Output
The maximum value.
Constraints
- 1 ≤ n ≤ 10^5
- -10^9 ≤ a[i] ≤ 10^9
Example 1
Input
4 3 9 2 7
Output
9
Example 2
Input
3 -5 -1 -9
Output
-1
Hints
- Assume the first element is the maximum, then look at every other element once.
- Don't start the maximum at 0 — all values could be negative.
Approach
Keep a running maximum initialised with a[0] and update it whenever a bigger element shows up. Starting from 0 (a classic bug) gives a wrong answer when every value is negative.
Complexity: O(n) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
long long best, x;
cin >> best;
for (int i = 1; i < n; i++) {
cin >> x;
best = max(best, x);
}
cout << best << "\n";
return 0;
}Python solution
import sys
data = sys.stdin.read().split()
n = int(data[0])
print(max(map(int, data[1 : n + 1])))Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long best = sc.nextLong();
for (int i = 1; i < n; i++) best = Math.max(best, sc.nextLong());
System.out.println(best);
}
}