This is a Microsoft / Amazon job interview type of question.
You can use a priority queue, in other to have the highest score as the first element of the queue. Create a node as key | value
pair. Implement it in a way the key order is maintained by the score value, and implement the queue.
Giving more details
This is your Node
implementation:
public class Node{
private String name; // the name
private double score; // assuming you're using double
public Node(String name, double score){
this.name = name;
this.score = score; // assuming negative scores are allowed
}
public void updateScore(double score){
this.score += score;
}
}
And when you use PriorityQueue
, make the Comparison
based on the score value. If you need to search / update, it is O(1), according to the Java API:
Implementation note: this implementation provides O(log(n)) time for
the enqueing and dequeing methods (offer, poll, remove() and add);
linear time for the remove(Object) and contains(Object) methods; and
constant time for the retrieval methods (peek, element, and size).
Read the API, I guess you probably need to overwrite the Comparator<? super E> comparator()
, or at least modify it for your needs. That should do it.