Compute fair bonuses
public static int[] calculateBonus(int[] ratings) {
// T stores the amount of bonus each one is assigned.
int[] T = new int[ratings.length];
Arrays.fill(T, 1);
// From left to right.
for (int i = 1; i < ratings.length; ++i) {
if (ratings[i] > ratings[i - 1]) {
T[i] = T[i - 1] + 1;
}
}
// From right to left.
for (int i = ratings.length - 2; i >= 0; --i) {
if (ratings[i] > ratings[i + 1]) {
T[i] = Math.max(T[i], T[i + 1] + 1);
}
}
return T;
}
public static int[] calculateBonus(int[] ratings) {
TreeSet<Pair<Integer, Integer>> h = new TreeSet<>(
new Comparator<Pair<Integer, Integer>>() {
@Override
public int compare(Pair<Integer, Integer> o1,
Pair<Integer, Integer> o2) {
int result = o1.getFirst().compareTo(o2.getFirst());
if (result == 0) {
result = o1.getSecond().compareTo(o2.getSecond());
}
return result;
}
}
);
for (int i = 0; i < ratings.length; ++i) {
h.add(new Pair<>(ratings[i], i));
}
// T stores the amount of bonus each one is assigned.
int[] T = new int[ratings.length];
Arrays.fill(T, 1);
// Fills T from lowest rating one to toppmost rating.
while (!h.isEmpty()) {
Pair<Integer, Integer> p = h.first();
// Handles the left neighbor.
if (p.getSecond() > 0) {
if (ratings[p.getSecond()] > ratings[p.getSecond() - 1]) {
T[p.getSecond()] = T[p.getSecond() - 1] + 1;
}
}
// Handles the right neighbor.
if (p.getSecond() + 1 < T.length) {
if (ratings[p.getSecond()] > ratings[p.getSecond() + 1]) {
T[p.getSecond()] = Math.max(T[p.getSecond()],
T[p.getSecond() + 1] + 1);
}
}
h.remove(p);
}
return T;
}