Start learning free

LESSON 190 OF 409 · NESTED LOOPS

Top K Brands V6 - Tie-Break by Review Count in C++

Practice

Rank the top k brands by rating, breaking ties with the review count. This builds on v4's repeated search (not on v5: there is no filtering here); only the comparison gets a second criterion.

You start with:

vector<string> brands = {"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"};
vector<int> ratings = {4, 5, 5, 3, 4};
vector<int> reviews = {200, 150, 500, 100, 300};
int k = 3;

Build:

1. NeoByte (5, 500)
2. MegaCorp (5, 150)
3. Zenith (4, 300)

Rules:

  • Rating decides first: the higher rating wins.
  • If two brands have the same rating, the one with more reviews wins.
  • If rating and reviews are both equal, the one listed first wins (the test data has no such pair, but your code must follow the rule).
  • k is never larger than the number of brands.
  • Each line is "rank. Brand (rating, reviews)", starting at rank 1.
  • Print the lines, one per line, with cout << ... << endl.

Start from v4: the same vector<bool> used(ratings.size(), false); and vector<string> lines;, the same two loops. Only the comparison inside the inner loop changes.

Use a chain (if / else if / else if): no candidate yet, take this one; else a higher rating, take this one; else the same rating and more reviews, take this one.

vector<string> brands = {"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"};
vector<int> ratings = {4, 5, 5, 3, 4};
vector<int> reviews = {200, 150, 500, 100, 300};
int k = 3;

vector<bool> used(ratings.size(), false);
vector<string> lines;
for (int rank = 1; rank <= k; rank++) {
    int bestIndex = -1;
    for (int i = 0; i < (int)ratings.size(); i++) {
        if (!used[i]) {
            if (bestIndex == -1) {
                bestIndex = i;
            }
            else if (ratings[i] > ratings[bestIndex]) {
                bestIndex = i;
            }
            else if (ratings[i] == ratings[bestIndex] && reviews[i] > reviews[bestIndex]) {
                bestIndex = i;
            }
        }
    }
    used[bestIndex] = true;
    lines.push_back(to_string(rank) + ". " + brands[bestIndex] + " (" + to_string(ratings[bestIndex]) + ", " + to_string(reviews[bestIndex]) + ")");
}
for (int i = 0; i < (int)lines.size(); i++) cout << lines[i] << endl;

STEP 1 OF 12
    Ctrl + Enter to check

    Top K Brands V6 in C++

    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free