Given an array of integers A, and an integer K find number of happy elements. Element X is happy if there exist at least 1 element whose difference is less than K i. e. an element X is another element in the range [X-K X+K] other than itself. Constraints 1<=N<=10^5 0<=K<=10^5 0<=A[i]<=10^9
Answers
Answer:
inp = input().split(" ")
n = int(inp[0])
k = int(inp[1])
arr = [int(i) for i in input().split()][:n]
count = 0
for x in range(n):
add = 0
sub = 0
add = arr[x] + k
sub = arr[x] - k
for j in range(n):
if j == x:
continue
else:
if arr[j] >= sub and arr[j]<= add:
count = count + 1
break
print(count,end="")
Edit:
inp = input().split(" ")
n = int(inp[0])
k = int(inp[1])
arr = [int(i) for i in input().split()][:n]
#for i in range(n):
# arr.append(int(input()))
count = 0
arr.sort()
for x in range(n):
add = arr[x] + k
sub = arr[x] - k
try:
if x+1 > len(arr)-1:
if arr[x-1]>=sub:
count = count + 1
elif x-1 < 0:
if arr[x+1]<= add:
count = count + 1
else:
if arr[x+1]<= add or arr[x-1]>=sub:
count = count + 1
except:
continue
print(count,end="")
got it to 1 sec but it is showing wrong answer
got it to 3 sec
JAVA CODE
import java.util.*;
class Main
{
public static int solve (int arr[], int n, int k)
{
int count = 0;
for (int i = 0; i < n; i++)
{
int a = arr[i];
int id1 = i;
int id2 = i;
if (i == 0)
{
while (arr[id2 + 1] == a)
id2 += 1;
if (arr[id2 + 1] <= a + k && arr[id2 + 1] >= a - k)
count += 1;
}
else if (i < n - 1)
{
while (arr[id2 + 1] == a)
id2 += 1;
while (arr[id1 - 1] == a)
id1 -= 1;
if (((arr[id1 - 1] <= a + k) && (arr[id1 - 1] >= a - k))|| ((arr[id2 + 1] <= a + k) && (arr[id2 + 1] >= a - k)))
count += 1;
}
else
{
while (arr[id1 - 1] == a)
id1 = id1 - 1;
if (arr[id1 - 1] <= a + k && arr[id1 - 1] >= a - k)
count += 1;
}
}
return count;
}
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
int n = sc.nextInt ();
int k = sc.nextInt ();
int arr[] = new int[n];
for (int i = 0; i < n; i++)
arr[i] = sc.nextInt ();
Arrays.sort (arr);
System.out.println (solve (arr, n, k));
}
}
#SPJ2