Created
January 3, 2012 10:33
-
-
Save phaniram/1554398 to your computer and use it in GitHub Desktop.
Interview Street Challenges - K Difference(Optimized)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.interviewstreet.puzzles; | |
| import java.util.Arrays; | |
| import java.util.Scanner; | |
| /** | |
| * | |
| * @author cypronmaya | |
| * K Difference - Interviewstreet Challenges (Optimal Solution) | |
| */ | |
| public class k_diff { | |
| public static void main(String args[]) { | |
| Scanner scanner = new Scanner(System.in); | |
| int total_nums = scanner.nextInt(); | |
| int diff = scanner.nextInt(); | |
| int ary_nums[] = new int[total_nums]; | |
| for (int i = 0; i < total_nums; i++) { | |
| ary_nums[i] = scanner.nextInt(); | |
| } | |
| int count = 0; | |
| Arrays.sort(ary_nums); | |
| for (int i = total_nums - 1; i > 0; i--) { | |
| for (int j = i - 1; j >= 0; j--) { | |
| if (ary_nums[i] - ary_nums[j] == diff) { | |
| count++; | |
| j = 0; | |
| } | |
| } | |
| } | |
| System.out.println(count); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
K Difference (50 Points)
Given N numbers , [N<=10^5] we need to count the total pairs of numbers that have a difference of K. [K>0 and K<1e9]
Input Format:
1st line contains N & K (integers).
2nd line contains N numbers of the set. All the N numbers are assured to be distinct.
Output Format:
One integer saying the no of pairs of numbers that have a diff K.
Sample Input #00:
5 2
1 5 3 4 2
Sample Output #00:
3
Sample Input #01:
10 1
363374326 364147530 61825163 1073065718 1281246024 1399469912 428047635 491595254 879792181 1069262793
Sample Output #01:
0
Note: Java/C# code should be in a class named "Solution"
Read input from STDIN and write output to STDOUT.