Anda di halaman 1dari 1

import java.util.

*;
class MaxSumMod {
public static void main(String args[]) {
int arr[] = {1, 2, 1, 2, 6, 5};
int k = 5;
// Look for two largest mod k
int max_i = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % k >= arr[max_i] % k) {
max_i = i;
}
}
int max_j = 0;
for (int j = 0; j < arr.length; j++) {
if (j != max_i && arr[j] % k >= arr[max_j] % k) {
max_j = j;
}
}
int max_value = (arr[max_i] + arr[max_j]) % k;
// Look for two that sums to under k
TreeMap<Integer, Integer> position = new TreeMap<Integer, Integer>();
for (int i = 0; i < arr.length; i++) {
position.put(arr[i] % k, i);
}
for (int i = 0; i < arr.length; i++) {
Integer key = position.lowerKey(k - (arr[i] % k));
if (key == null) continue;
int j = position.get(key);
if (i == j) continue;
int value = (arr[i] + arr[j]) % k;
if (value > max_value) {
max_i = i;
max_j = j;
max_value = value;
}
}
System.out.println(arr[max_i] + " " + arr[max_j]);
}
}