saurav_kalsoor

Find Pair - JAVA

Jul 27th, 2021 (edited)
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.92 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Scanner;
  6.  
  7. public class Problem {
  8.  
  9.     public static void main(String[] args){
  10.         Scanner sc = new Scanner(System.in);
  11.         int n = sc.nextInt();
  12.         int x = sc.nextInt();
  13.  
  14.         ArrayList<Integer> list = new ArrayList<>();
  15.  
  16.         for(int i=0; i<n; i++){
  17.             int num = sc.nextInt();
  18.             list.add(num);
  19.         }
  20.         System.out.println(findPair(list, x, n));
  21.  
  22.     }
  23.  
  24.     public static int findPair(ArrayList<Integer> list, int x, int n){
  25.         Collections.sort(list);
  26.         int i = 0, j = n - 1;
  27.         while (i < j){
  28.             if(list.get(i) + list.get(j) == x)
  29.                 return Math.abs(list.get(i) - list.get(j));
  30.             else if(list.get(i) + list.get(j) < x)
  31.                 i++;
  32.             else
  33.                 j--;
  34.         }
  35.         return -1;
  36.     }
  37. }
Add Comment
Please, Sign In to add comment