2. Largest three elements in an array
Find the largest three elements in an array with O(1) space and O(n) time complexity
Input: 5
1 2 3 4 5
Output: 3 4 5
Method:
1. Initialize three variables first, second and third with minimum value.
2. If you find an element greater than first element then move second to third, first to second and array element to first.
3. Else if you find an element greater than second element then move second to third and array element to second.
4. Else if you find an element greater than than third element then move that element to third position.
Key point: We are using third variable like a temporary variable here. Because when we find an element to fit in one of first three positions then we definitely don't need that third element ever.
Code:
import java.io.*;
import java.util.*;
class ArrayMaxElements {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
int third = Integer.MIN_VALUE;
int n = in.nextInt();
int arr[] = new int[n];
for(int i=0; i<n; i++){
arr[i] = in.nextInt();
}
for(int i=0; i<n; i++){
if(arr[i]>first){
third = second;
second = first;
first = arr[i];
}
else if(arr[i]> second){
third = second;
second = arr[i];
}
else if(arr[i]> third){
third = arr[i];
}
}
System.out.println(first+" "+second+" "+third);
}
}
Input: 5
1 2 3 4 5
Output: 3 4 5
Method:
1. Initialize three variables first, second and third with minimum value.
2. If you find an element greater than first element then move second to third, first to second and array element to first.
3. Else if you find an element greater than second element then move second to third and array element to second.
4. Else if you find an element greater than than third element then move that element to third position.
Key point: We are using third variable like a temporary variable here. Because when we find an element to fit in one of first three positions then we definitely don't need that third element ever.
Code:
import java.io.*;
import java.util.*;
class ArrayMaxElements {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
int third = Integer.MIN_VALUE;
int n = in.nextInt();
int arr[] = new int[n];
for(int i=0; i<n; i++){
arr[i] = in.nextInt();
}
for(int i=0; i<n; i++){
if(arr[i]>first){
third = second;
second = first;
first = arr[i];
}
else if(arr[i]> second){
third = second;
second = arr[i];
}
else if(arr[i]> third){
third = arr[i];
}
}
System.out.println(first+" "+second+" "+third);
}
}
Comments
Post a Comment