Java bootcamp · Lab 20

Second largest

mediumArrays12 minLesson: Arrays

Read the question, write Java on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read n (≥2) then n distinct integers. Print the second largest.

Examples

Example 1
Input
4
3 1 8 2
Output
3
Hint
  1. Track first and second while scanning.
Show correct code

Peek only after you have tried. You can still Check your own version.

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
    for (int i = 0; i < n; i++) {
      int x = in.nextInt();
      if (x > first) { second = first; first = x; }
      else if (x > second) second = x;
    }
    System.out.println(second);
  }
}
Main.javaJava 21 · javac · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.