Advertisement
jasonpogi1669

Max Element within a Subsegment using Collections in Java

Aug 7th, 2022
871
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.47 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class Test {
  5.     public static void main(String[] args) {
  6.         ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(9, 1, 7, 10, 1, 5, 4, 6));
  7.        
  8.         Scanner sc = new Scanner(System.in);
  9.         int k = sc.nextInt();
  10.         sc.close();
  11.        
  12.         if (k > arr.size()) {
  13.             System.out.println("Invalid");
  14.             return;
  15.         }
  16.        
  17.         //max element among the first k elements
  18.         int mx = Collections.max(arr.subList(0, k));
  19.         System.out.println(mx);
  20.     }
  21. }
  22.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement