Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Scanner;
- public class Problem {
- public static void main(String[] args){
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt();
- int x = sc.nextInt();
- ArrayList<Integer> list = new ArrayList<>();
- for(int i=0; i<n; i++){
- int num = sc.nextInt();
- list.add(num);
- }
- System.out.println(findPair(list, x, n));
- }
- public static int findPair(ArrayList<Integer> list, int x, int n){
- Collections.sort(list);
- int i = 0, j = n - 1;
- while (i < j){
- if(list.get(i) + list.get(j) == x)
- return Math.abs(list.get(i) - list.get(j));
- else if(list.get(i) + list.get(j) < x)
- i++;
- else
- j--;
- }
- return -1;
- }
- }
Add Comment
Please, Sign In to add comment