Problem statement

https://binarysearch.com/problems/Highest-Volume-Stocks/

Solution

The idea is to keep for each name value and also keep sortedlist of all pairs (name, value).

Complexity

It is O(n log n) for init, O(log n) for add and O(k log k) for top.

Code

class StockMarket:
    def __init__(self, stocks, amounts):
        self.scores = Counter()
        for s, a in zip(stocks, amounts):
            self.scores[s] = a
        self.SList = SortedList([(-a, s) for s, a in zip(stocks, amounts)])
        print(self.SList)

    def add(self, s, amount):
        if s in self.scores: self.SList.remove((-self.scores[s], s))
        self.scores[s] += amount
        self.SList.add((-self.scores[s], s))
 
    def top(self, K):
        return [self.SList[i][1] for i in range(K)]

Remark

Similar logic can be implemented with heaps.