Problem Description
Given an one-dimensional unsorted array A containing N integers.
You are also given an integer B, find if there exists a pair of elements in the array whose difference is B.
Print 1 if any such pair exists else print 0.
Problem Constraints 1 <= N <= 100000 -1000 <= A[i] <= 1000 -100000 <= B <= 100000
Input Format First line contains n (size of the array) Second line contains n elements of the array Third line contains integer B.
Output Format Print 1 if any such pair exists else print 0.
Example I
Input 1: 6 5 10 3 2 50 80 78
Input 2: 2 -10 20 30
Example Output
Output 1:
1
Output 2:
1
Example
Explanation 1:
Pair (80, 2) gives a difference of 78.
Explanation 2:
Pair (20, -10) gives a difference of 30 i.e 20 – (-10) => 20 + 10 => 30
Solution of Problem With Given Difference in java:–
import java.util.*; import java.lang.*; import java.io.*; public class Main { public static void main (String[] args) throws java.lang.Exception { //your code here Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int arr[] = new int[n]; for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); } int b=sc.nextInt(); int count=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if((arr[i]-arr[j])==b) { count++; break; } } } if(count>0) { System.out.println(1); } else{ System.out.println(0); } } }
Add a Comment