Advertisement
Foltrex2002

Home assignment

May 23rd, 2024
686
0
5 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.89 KB | None | 0 0
  1. import java.util.List;
  2.  
  3. class HelloWorld {
  4.     public static void main(String[] args) {
  5.         List<Integer> arr = List.of(-15, 7, 0, 88, 33, 15);
  6.         System.out.println(getSecondLargestInteger(arr));
  7.     }
  8.    
  9.     public static Integer getSecondLargestInteger(List<Integer> arr) {
  10.         if (arr == null || arr.size() < 2) {
  11.             throw new IllegalArgumentException("Array must contain at least 2 values");
  12.         }
  13.  
  14.         int largest = arr.get(0);
  15.         int secondLargest = Integer.MIN_VALUE;
  16.    
  17.         for (int current : arr) {
  18.             if (current > largest) {
  19.                 secondLargest = largest;
  20.                 largest = current;
  21.             } else if (current > secondLargest && current != largest) {
  22.                 secondLargest = current;
  23.             }
  24.         }
  25.    
  26.         return secondLargest == Integer.MIN_VALUE ? null : secondLargest;
  27.     }
  28. }
Tags: Interview
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement