Help me in solving TACHSTCK problem i dont knoe whats doing wrong with my code pls help me

My issue

My code

#include <iostream>
#include<algorithm>
using namespace std;

int main() {
	// your code goes here
   	int n,k,i;
	cin>>n>>k;
	 int a[n];
    for(i=0;i<n;i++)
    {
        cin>>a[i];
    }
     i=0;
    sort(a,a+n);
    int count=0;
    for(i=0;i<n-1;i=i+2)
    {
        if(a[i+1]-a[i]<=k)
        {
          count++;  
        }
    }
    cout<<count<<endl;
	return 0;
}

Problem Link: TACHSTCK Problem - CodeChef

@kjha1893
u have to increment it twice only when to get a valid answer else u don’t increment it twice.
i have written the code with same logic as yours . hope u will get it.
include <bits/stdc++.h>
using namespace std;

int main() {
// your code goes here

int n,d;
cin>>n>>d;
int a[n];
for(int i=0;i<n;i++)
{
    cin>>a[i];
 }
 sort(a,a+n);
 int ans=0;
 for(int i=1;i<n;i++)
 {
     if(a[i]-a[i-1]<=d)
     {
         ans++;
         i++;
     }
 }
 cout<<ans;

}

1 Like

thank you