DIFFICULTY:
CAKEWALK PREREQUISITES:
None PROBLEM:
You’re given sequence A_1, \dots, A_n. Find out maximum possible A_i \bmod A_j. QUICK EXPLANATION:
Sort in descending order, remove duplicates. Answer is A_2 \bmod A_1 now. EXPLANATION:
If all numbers are equal, answer is 0. Otherwise let largest element in sequence be a and second largest element which is not equal to a be b. Note that b \bmod a = b, now if A_i \bmod A_j > b then A_j > b, thus A_j = a. But since all elements are at most a, largest remainder modulo a is b:
int main() {
int n;
cin >> n;
int a[n];
for(int i = 0; i < n; i++) {
cin >> a[i];
}
sort(a, a + n, greater<int>());
unique(a, a + n);
cout << a[1] % a[0] << endl;
return 0;
}
AUTHOR’S AND TESTER’S SOLUTIONS:
Author’s solution can be found here.
Tester’s solution can be found here.
Editorialist’s solution can be found here.
Seems there is problem with this in python, half the test cases are accepted with AC.
Remaining test cases are giving NZEC error. I have no clue of how and why is this happening.
n = int(input())
l = list(map(int, input().split()))
l = list(set(l))
l.sort()
print(l[-2] % l[-1])
brother !
you havent consider the case when all the inputs are same .
In that case after applying set only one element in l so l[-2] will give you error. @aditya_oke
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
int n;
cin >> n;
int x[n];
for(int i = 0; i < n; i++) {
cin >> x[i];
}
sort(x, x + n, greater<int>());
int hld = x[0];
int ans = 0;
for(int i = 0; i < n; i++) {
if(x[i] != hld) {
ans = x[i];
break;
}
}
cout << ans << endl;
}
An easy way to avoid the corner case (when all the elements are equal) is to set the variable ans default to 0. So when all the elements are the same, that means that there are no distinction between the elements, so the for loop will never encounter a distinct element so the ans variable won’t change. So the answer would be ‘0’.