Skip to content

Instantly share code, notes, and snippets.

@kkuivi
Created December 4, 2017 09:17
Show Gist options
  • Save kkuivi/ae6537e7a400d6db8cf33123e8c32797 to your computer and use it in GitHub Desktop.
Save kkuivi/ae6537e7a400d6db8cf33123e8c32797 to your computer and use it in GitHub Desktop.
Hackerland Radio Transmitters
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int[] x = new int[n];
for(int x_i=0; x_i < n; x_i++){
x[x_i] = in.nextInt();
}
ArrayList<Integer> uniqueNums = getUniqueNums(x);
Collections.sort(uniqueNums);
Range[] ranges = getRanges(uniqueNums, k);
int numTransmitters = getNumTransmitters(ranges);
System.out.println(numTransmitters);
}
public static class Range {
int value;
int low;
int high;
Range(int value, int low, int high) {
this.value = value;
this.low = low;
this.high = high;
}
}
public static ArrayList<Integer> getUniqueNums(int[] nums) {
HashSet<Integer> uniqueNums = new HashSet<Integer>();
for(int n : nums) {
uniqueNums.add(n);
}
ArrayList<Integer> result = new ArrayList<Integer>();
result.addAll(uniqueNums);
return result;
}
public static Range[] getRanges(ArrayList<Integer>, int k) {
Range[] result = new Range[nums.size()];
for(int i = 0; i < nums.size(); i++) {
int lowestPossible = nums.get(i) - k;
int highestPossible = nums.get(i) + k;
int currLow = nums.get(i);
int currHigh = nums.get(i);
for(int j = i; j >= 0; j--) {
if(nums.get(j) >= lowestPossible)
currLow = nums.get(j);
else
break;
}
for(int k = i; j < nums.size(); j++) {
if(nums.get(k) <= highestPossible)
currHigh = nums.get(k);
else
break;
}
result[i] = new Range(nums.get(i),currLow, currHigh);
}
return result;
}
public static int getNumTransmitters(Range[] ranges) {
int result = 0;
int currK = -1;
int currLow = -1;
int currHigh = -1;
int i = 0;
while(i < ranges.length) {
if(currK == -1) {
currK = ranges[i].value;
currLow = ranges[i].value;
currHigh = ranges[i].high;
}
else if(ranges[i].low == currLow && ranges[i].high > currHigh) {
currK = ranges[i].value;
currLow = ranges[i].low;
currHigh = ranges[i].high;
}
else {
result++;
while(i < ranges.length && ranges[i].value <= currHigh) {
i++;
}
currK = -1;
currLow = -1;
currHigh = -1;
}
}
if(currK == -1)
result++;
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment