Finding the second highest number in array in Java

algorithm, arrays, java

Solution

I'm not convinced that doing what you did fixes the problem; I think it masks yet another problem in your logic. To find the second highest is actually quite simple:

 static int secondHighest(int... nums) {
    int high1 = Integer.MIN_VALUE;
    int high2 = Integer.MIN_VALUE;
    for (int num : nums) {
      if (num > high1) {
        high2 = high1;
        high1 = num;
      } else if (num > high2) {
        high2 = num;
      }
    }
    return high2;
 }

This is `O(N)` in one pass. If you want to accept ties, then change to `if (num >= high1)`, but as it is, it will return `Integer.MIN_VALUE` if there aren't at least 2 elements in the array. It will also return `Integer.MIN_VALUE` if the array contains only the same number.

Problem

I'm having difficulty to understand the logic behind the method to find the second highest number in array. The method used is to find the highest in the array but less than the previous highest (which has already been found). The thing that I still can't figure it out is why `|| highest_score == second_highest` is necessary. For example I input three numbers: 98, 56, 3. Without it, both highest and second highest would be 98. Please explain. ``` int second highest = score[0]; if (score[i] > second_highest && score[i] < highest_score || highest_score == second_highest) second_highest = score[i]; ```

Original source

Related problems