Problem overview
The brands now have a second number. Three parallel arrays describe them: brands, ratings and reviews, the number of reviews behind each rating. The program prints the top k brands, best first, one per line, in the form rank. Brand (rating, reviews).
The rating decides first. If two brands have the same rating, the one with more reviews wins. If the rating and the review count are both equal, the brand listed first wins. For the starting data and k = 3, NeoByte and MegaCorp both have rating 5, and NeoByte has 500 reviews against 150. Zenith (4, 300) comes next, ahead of TechPro (4, 200):
1. NeoByte (5, 500)
2. MegaCorp (5, 150)
3. Zenith (4, 300)
The lesson says k is never larger than the number of brands.
Approach: version 4's search with a second criterion
This version builds on the repeated search from version 4, and no filtering is involved. Each round scans the brands that aren't taken yet, keeps the best one found so far, marks the round's winner as taken and records a line. Only the question "is this brand better than the best so far?" changes.
That question now has three cases, checked in order:
- Nothing has been found yet in this round, so this brand is the best so far.
- This brand's rating is higher than the best one's, so it becomes the best, whatever the reviews are.
- The ratings are equal and this brand has more reviews, so it becomes the best.
Because the comparisons are strict, a brand that matches the best one on both numbers never replaces it, so the brand listed first stays ahead.
Step by step
- Create
used. Abooleanarray with a slot per brand, allfalse: nobody has a rank yet. - Create
lines. An emptyArrayListof strings, for one finished line per rank. - Write the outer loop.
rankfrom 1 up to and includingk. It counts the rounds and is printed in front of each brand. - Reset
bestIndex.int bestIndex = -1;means nothing found yet, and each round starts the search over. - Write the inner loop.
itakes every position ofratings, so each round looks at all the brands from the start. - Skip taken brands.
if (!used[i])keeps the brands that already have a rank out of the search. - First case. If
bestIndexis -1, set it toi: the first brand not taken has nobody to beat. - Second case. With
else if, a higher rating makes this brand the best. A case in the chain runs only when the ones above it were false. - Third case. With another
else if, the ratings are equal and the review count is higher. Both parts must hold, because reviews only break a tie. - Mark the winner. After the inner loop, set
used[bestIndex]totrue. - Add the line. The rank, a dot and a space, the brand, then the rating and the review count in parentheses, separated by a comma and a space.
- Print.
String.join("\n", lines)insideSystem.out.printlnputs each rank on its own line.
The solution in Java
String[] brands = {"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"};
int[] ratings = {4, 5, 5, 3, 4};
int[] reviews = {200, 150, 500, 100, 300};
int k = 3;
boolean[] used = new boolean[ratings.length];
List<String> lines = new ArrayList<>();
for (int rank = 1; rank <= k; rank++) {
int bestIndex = -1;
for (int i = 0; i < ratings.length; 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.add(rank + ". " + brands[bestIndex] + " (" + ratings[bestIndex] + ", " + reviews[bestIndex] + ")");
}
System.out.println(String.join("\n", lines));
The Java details worth a closer look:
- Chain order is part of the logic. The
bestIndex == -1case comes first because the two cases below it readratings[bestIndex]. With -1 they would throw an exception. The chain never reaches them while that first case is true. ==onintis a value comparison. Hereratings[i] == ratings[bestIndex]compares numbers, which is correct for primitives. (Objects likeStringneedequals.)&&for "both". The third case needs the ratings to be equal and the reviews to be higher. Writing it with||would let a lower-rated brand with many reviews win.- Parallel arrays share an index. One
bestIndexreads the name, the rating and the review count, which is why all three arrays must keep the same order.
Complexity
Time: O(k * n) for n brands. Each of the k rounds scans all n positions, and every comparison takes constant time. When k equals n, this is O(n²).
Space: O(n + k): the used flags and the lines list.
Edge cases and common mistakes
- Dropping the "equal rating" test. If the third case only checks
reviews[i] > reviews[bestIndex], a brand with a lower rating but more reviews can take the place of a better one. With two brands rated 5 with 10 reviews and 3 with 99 reviews, the loose chain picks the second brand, and the correct chain picks the first. - Reviews first. Ranking by reviews alone puts NeoByte (5, 500) first for the starting data, which happens to be right, but it breaks for any pair like the one above. The rating is the main criterion.
- Full ties. With the same rating and the same reviews, the brand listed first stays first. For brands A (5, 10), B (5, 10) and C (3, 99) and
k = 2, the output is A, then B. kequal to the number of brands. Withk = 5the starting data prints NeoByte (5, 500), MegaCorp (5, 150), Zenith (4, 300), TechPro (4, 200) and Quantum (3, 100).klarger than the number of brands. The lesson rules this out. Without a check, a round with no brand left would leavebestIndexat -1, andused[-1]would throw an exception.- Forgetting to mark the winner or to reset
bestIndex. Either one makes later rounds repeat or compare against stale data.
Testing
- The starting data with
k = 3prints the three lines above. - The starting data with
k = 5prints five lines, ending with5. Quantum (3, 100). - Brands A (5, 10), B (5, 10) and C (3, 99) with
k = 2print1. A (5, 10)and2. B (5, 10).
