- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 95 lines of C++ from the credited upstream file design-auction-system.cpp.
- The implementation visibly relies on hash lookup, ordered lookup, work queue.
- 1 loop block detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1234567 89class AuctionSystem {10public:11 AuctionSystem() {12 13 }14 15 void addBid(int userId, int itemId, int bidAmount) {16 bids_[itemId][userId] = bidAmount;17 bidders_[itemId].emplace(bidAmount, userId);18 }19 20 void updateBid(int userId, int itemId, int newAmount) {21 addBid(userId, itemId, newAmount);22 }23 24 void removeBid(int userId, int itemId) {25 bids_[itemId].erase(userId);26 if (empty(bids_[itemId])) {27 bids_.erase(itemId);28 }29 }30 31 int getHighestBidder(int itemId) {32 if (!bidders_.count(itemId)) {33 return -1;34 }35 while (!empty(bidders_[itemId])) {36 const auto [p, u] = bidders_[itemId].top();37 if (bids_[itemId][u] == p) {38 return u;39 }40 bidders_[itemId].pop();41 }42 bidders_.erase(itemId);43 return -1;44 }45 46private:47 unordered_map<int, unordered_map<int, int>> bids_;48 unordered_map<int, priority_queue<pair<int, int>>> bidders_;49};50 5152535455565758class AuctionSystem2 {59public:60 AuctionSystem2() {61 62 }63 64 void addBid(int userId, int itemId, int bidAmount) {65 if (bids_[itemId].count(userId)) {66 bidders_[itemId].erase({bids_[itemId][userId], userId});67 }68 bids_[itemId][userId] = bidAmount;69 bidders_[itemId].emplace(bidAmount, userId);70 }71 72 void updateBid(int userId, int itemId, int newAmount) {73 addBid(userId, itemId, newAmount);74 }75 76 void removeBid(int userId, int itemId) {77 bidders_[itemId].erase({bids_[itemId][userId], userId});78 if (empty(bidders_[itemId])) {79 bidders_.erase(itemId);80 }81 bids_[itemId].erase(userId);82 if (empty(bids_[itemId])) {83 bids_.erase(itemId);84 }85 }86 87 int getHighestBidder(int itemId) {88 return bidders_.count(itemId) ? rbegin(bidders_[itemId])->second : -1;89 }90 91private:92 unordered_map<int, unordered_map<int, int>> bids_;93 unordered_map<int, set<pair<int, int>>> bidders_;94};95