Start learning free

LESSON 188 OF 409 · NESTED LOOPS

Top K Brands V4 - Top K in C++

Practice

Show the top k brands by rating. This is v3's search, repeated k times: find the best brand, mark it as taken, then search again among the brands that are not taken yet, until you have k brands in rank order.

You start with:

vector<string> brands = {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"};
vector<int> ratings = {4, 5, 3, 5, 4};
int k = 3;

Build:

1. MegaCorp (5)
2. NeoByte (5)
3. TechPro (4)

Rules:

  • Repeat v3's search k times. Each round looks only at brands that are not taken yet and picks the one with the highest rating, then marks it as taken (one true/false flag per brand).
  • Ties go to the brand listed first: keep the first brand you find and replace it only on a strictly higher rating.
  • k is never larger than the number of brands.
  • Each line is "rank. Brand (rating)", starting at rank 1.
  • Print the lines, one per line, with cout << ... << endl.

Start with the two declarations vector<bool> used(ratings.size(), false); and vector<string> lines;. A flag tells whether that position is already taken.

Each round is v3's search: nothing found yet, scan every position, skip taken ones, keep the first candidate and replace it only on a strictly higher rating. Then mark the winner as taken and add its line.

vector<string> brands = {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"};
vector<int> ratings = {4, 5, 3, 5, 4};
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 || ratings[i] > ratings[bestIndex]) {
                bestIndex = i;
            }
        }
    }
    used[bestIndex] = true;
    lines.push_back(to_string(rank) + ". " + brands[bestIndex] + " (" + to_string(ratings[bestIndex]) + ")");
}
for (int i = 0; i < (int)lines.size(); i++) cout << lines[i] << endl;

STEP 1 OF 11
    Ctrl + Enter to check

    Top K Brands V4 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