In this post, we will solve HackerRank Radio Transmitters HackerRank Solution. This problem (HackerRank Radio Transmitters) is a part of HackerRank Problem Solving series.
Solution – HackerRank Radio Transmitters – HackerRank Solution
C++
#include <bits/stdc++.h> typedef long long LL; using namespace std; int main(){ int n, k; cin >> n >> k; int x[n]; for(int i = 0; i < n; i++) scanf("%d", &x[i]); sort(x,x+n); int ans = 0; int cur = 0; while(cur < n){ int st = x[cur]; while(cur < n && x[cur+1] <= st+k){ cur++; } int m = x[cur]; while(cur < n && x[cur+1] <= m+k){ cur++; } ans++; cur++; } cout << ans << endl; }
Python
n,k = input().strip().split(' ') n,k = [int(n),int(k)] x = [int(x_temp) for x_temp in input().strip().split(' ')] x.sort() count=0 length=len(x) i=0 while i<length: temp=x[i] while length>i and x[i]-temp<=k: i+=1 head=x[i-1] while length>i and x[i]-head<=k: i+=1 count+=1 print(count)
Java
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(); } Arrays.sort(x); int left = 0,right,mid, ans = 0; int end; while(left < n) { right = left; mid = left; ans++; while(mid < n && x[mid] - x[left] <= k) { mid++; // mid will be out } mid--; end = x[mid] + k; right = mid + 1; while(right < n && x[right] <= end) { right++; } left = right; } System.out.println(ans); } }
Note: This problem (HackerRank Radio Transmitters) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose only.