Developing Algorithms Using Arrays

AP Computer Science A· difficulty 5/5

int[] a = {3, 8, 5, 8, 2, 7};
int max = a[0];
int second = -1;
for (int i = 1; i < a.length; i++) {
  if (a[i] > max) {
    second = max;
    max = a[i];
  } else if (a[i] < max && a[i] > second) {
    second = a[i];
  }
}
System.out.println(second);

What is printed?

  • A

    7

    check_circle
  • B

    8

  • C

    3

  • D

    5

Explanation

The algorithm tracks the largest strictly less than max. The maximum is 8 (with a duplicate 8), and the second-largest distinct value is 7.

Want 10 more like this — adaptive to your weak spots?

Related questions