Third Maximum Distinct Number
Problem
Print the third biggest different value of the array. If the array has fewer than three different values, print the biggest value instead. Equal numbers count as one value.
Constraints
- 1 <= n <= 10^5
- |a[i]| <= 10^9
Examples
Input
4 2 2 3 1
Output
1
Solutions
Three variables hold the biggest, second and third different values. A new value is placed in its slot and the lower ones move down. One pass, O(1) memory.
/*
* Problem : Third maximum.
* Input : n, then n integers.
* Output : One number.
* Approach: Three variables.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static long solve(int[] a) {
// Step 1: Keep the three biggest different values seen so far. Long.MIN_VALUE means "not set yet".
long first = Long.MIN_VALUE;
long second = Long.MIN_VALUE;
long third = Long.MIN_VALUE;
for (int value : a) {
// Step 2: Skip a value that we already have. Otherwise put it in the right place and push the others down.
if (value == first || value == second || value == third) {
continue;
}
if (value > first) {
third = second;
second = first;
first = value;
} else if (value > second) {
third = second;
second = value;
} else if (value > third) {
third = value;
}
}
// Step 3: If there is no third value, the answer is the biggest.
return third == Long.MIN_VALUE ? first : third;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(solve(a));
}
}
Hints (2)
- Why is a repeated value skipped?
- What marks an empty slot?