andreiko489

LargestThree

Jan 18th, 2022 (edited)
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.06 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class LargestThree {
  4.     public static void main(String... args) {
  5.         Scanner in = new Scanner(System.in);
  6.  
  7.         int numbersCount = in.nextInt();
  8.  
  9.         int n1 = Integer.MIN_VALUE; // largest
  10.         int n2 = Integer.MIN_VALUE; // second largest
  11.         int n3 = Integer.MIN_VALUE; // third largest
  12.  
  13.         int x;
  14.  
  15.         for (int i = 0; i < numbersCount; ++i) {
  16.             x = in.nextInt();
  17.             if (n1 < x) { // is greater than the largest
  18.                 n3 = n2;
  19.                 n2 = n1;
  20.                 n1 = x;
  21.             } else if (n2 < x) { // is not greater than the largest but is greater than the second largest
  22.                 n3 = n2;
  23.                 n2 = x;
  24.             } else if (n3 < x) { // is not greater than the second largest but is greater than the third largest
  25.                 n3 = x;
  26.             }
  27.             // if we are here, then is not greater than the third largest so we do not care and just skip it
  28.         }
  29.  
  30.         System.out.printf("%d, %d and %d", n1, n2, n3);
  31.     }
  32. }
  33.  
Add Comment
Please, Sign In to add comment