TACHSTCK: Chopsticks
Link for the problem: TACHSTCK
SOLUTION:
Pairs can be formed by just greater or just smaller chopstick for a particular chopstick. So the problem can be solved by just sorting.
CODE:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,d,i,j,k,s=0;
cin>>n>>d;
int a[n];
for(i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
for(i=0;i<n-1;)
{
if(a[i+1]-a[i]<=d)
{
s+=1;
i+=2;
}
else
i++;
}
cout<<s<<endl;
return 0;
}
Link for the problem: TACHSTCK
SOLUTION:
Pairs can be formed by just greater or just smaller chopstick for a particular chopstick. So the problem can be solved by just sorting.
CODE:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,d,i,j,k,s=0;
cin>>n>>d;
int a[n];
for(i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
for(i=0;i<n-1;)
{
if(a[i+1]-a[i]<=d)
{
s+=1;
i+=2;
}
else
i++;
}
cout<<s<<endl;
return 0;
}
check for input N = 6 D = 4
ReplyDeletea[] = {9,2,5,6,7,8};
after sorting the array becomes 2 5 6 7 8 9
Deleteand your comparisons are only to left stick which gives a s = 0 while answer should 2. try using hashmap instead.