Start learning free

LESSON 185 OF 671 · LOOPING OVER ARRAY INDICES

Top K Brands V3 in Java: Max of an Array with a Loop

Practice Read the full explanation

Many brands sell the same product, stored in two parallel arrays: ratings[i] is the rating of brands[i]. Find the highest-rated brand by scanning with a loop.

You start with:

String[] brands = {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"};
int[] ratings = {4, 5, 3, 5, 4};

Build:

1. MegaCorp (5)

Rules:

  • Keep the position of the best brand so far in bestIndex, starting at 0, and scan the positions from 1 to the end with a loop.
  • Update bestIndex only on a strictly higher rating. If two brands share the top rating, the one listed first wins (MegaCorp at position 1, not NeoByte at position 3).
  • Format the winner as "1. Brand (rating)" and print it with System.out.println(...).

Walk the positions with for (int i = 1; i < ratings.length; i++) { and compare each rating with the best one so far.

Java converts the int to text when you join it to a String with +.

String[] brands = {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"};
int[] ratings = {4, 5, 3, 5, 4};

int bestIndex = 0;
for (int i = 1; i < ratings.length; i++) {
    if (ratings[i] > ratings[bestIndex]) {
        bestIndex = i;
    }
}
System.out.println("1. " + brands[bestIndex] + " (" + ratings[bestIndex] + ")");

STEP 1 OF 5
    Ctrl + Enter to check

    JAVA · LOOPING OVER ARRAY INDICES

    Top K Brands V3 in Java, explained

    Problem overview

    Many brands now sell the same product. They are stored in two parallel arrays: ratings[i] is the rating of brands[i]. The program must find the highest-rated brand with a loop and print it as 1. Brand (rating). If two brands share the top rating, the one listed first wins.

    With {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"} and ratings {4, 5, 3, 5, 4}, the top rating 5 belongs to both MegaCorp (position 1) and NeoByte (position 3). MegaCorp is listed first, so it wins:

    1. MegaCorp (5)

    Approach: keep the best position so far

    Finding a maximum is a classic scan. Assume the first element is the best, then look at every other element and replace the champion whenever an element beats it. After one pass, the champion is the maximum.

    The program stores the position of the best brand in bestIndex, not its rating. A position works in both arrays: brands[bestIndex] is the name and ratings[bestIndex] is the rating, so the final line needs nothing else.

    The update uses a strictly greater comparison. When a later brand only ties, it does not replace the earlier one, and that implements "the first listed wins".

    Step by step

    1. Create bestIndex and set it to 0. For now the first brand is the best one known.
    2. Write a for loop where i starts at 1 and goes up by one while i < ratings.length. Position 0 is already the champion, so there is no reason to compare it with itself.
    3. Inside the loop, write an if comparing ratings[i] with ratings[bestIndex], strictly greater.
    4. Inside the if, set bestIndex to i. This brand is the new best, so remember where it is.
    5. After the loop, print "1. ", brands[bestIndex], " (", ratings[bestIndex] and ")", joined with +.

    The solution in Java

    String[] brands = {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"};
    int[] ratings = {4, 5, 3, 5, 4};
    int bestIndex = 0;
    for (int i = 1; i < ratings.length; i++) {
        if (ratings[i] > ratings[bestIndex]) {
            bestIndex = i;
        }
    }
    System.out.println("1. " + brands[bestIndex] + " (" + ratings[bestIndex] + ")");
    

    The condition i < ratings.length stops before the index equal to the length, since valid indexes of an array run from 0 to length - 1. Here length is a field, so there are no parentheses after it. The loop also assumes the two arrays have the same length, as parallel arrays should.

    Tracing the loop

    iratings[i]bestIndex after the check
    151 (5 > 4)
    231
    351 (5 is not greater than 5)
    441

    Before the loop, bestIndex was 0 with rating 4. At the end it is 1, so the program prints brands[1], MegaCorp, and its rating 5. At i = 3 NeoByte ties and does not take the lead.

    Complexity

    The loop looks at each rating once, so the time is O(n) for n brands. Only a few variables are used besides the input, so the extra space is O(1).

    Edge cases and common mistakes

    Ties

    With >= in the condition, NeoByte would replace MegaCorp at i = 3 and the output would be 1. NeoByte (5), which breaks the rule. A short test with two brands both rated 2 confirms the strict version: the program prints the first one, 1. A (2), for brands {"A", "B"}.

    Starting the loop at 0 or ending it too late

    Starting at 0 only wastes one comparison, since an element never beats itself. Ending with i <= ratings.length is a real bug: the last pass reads ratings[5] in an array of 5 elements and throws ArrayIndexOutOfBoundsException.

    Remembering the rating but not the position

    If you keep only the best rating in a variable, you can print the number but cannot tell which brand it belongs to. The index solves both at once.

    Empty arrays

    The solution assumes at least one brand. With empty arrays, the final line reads index 0 of an empty array and throws an exception, so a program that accepts arbitrary input must check the length first.

    Key takeaways

    • A maximum is found by keeping the best so far and updating it during one pass.
    • With parallel arrays, store the index: it gives you every attribute.
    • Use a strict comparison so that the earliest of equal values stays in front.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free