I can’t find the issue with this solution… It passes all test cases except 3 and 6…
Problem Link
#include <bits/stdc++.h>
using namespace std;
int main() {
//freopen("diamond.in","r",stdin);
//freopen("diamond.out","w",stdout);
int N, K;
cin >> N >> K;
vector<int> size(N);
for (int i=0; i<N; i++) {
cin >> size[i];
}
sort(size.begin(),size.end());
int left = 0;
int right = 0;
int ans1 = 0;
vector<tuple<int,int,int>> minarray;
while (left!=(N-1)) {
if ((size[right]-size[left])<=K) {
if (right<(N-1)) {
right++;
}
else {
break;
}
}
else {
if (max(ans1,(right-left)) > ans1) {
ans1 = max(ans1,(right-left));
minarray.push_back({right-left,left,right});
}
left++;
}
}
vector<int> size2;
sort(minarray.begin(),minarray.end());
int last = get<0>(minarray[minarray.size()-1]);
int maximum=0;
int ans2 = 0;
for (int i=0; i<minarray.size(); i++) {
size2 = size;
size2.erase(size2.begin()+get<1>(minarray[i]), size2.begin()+get<2>(minarray[i]));
ans1 = get<2>(minarray[i])-get<1>(minarray[i]);
N = size2.size();
left = 0;
right = 0;
ans2 = 0;
while (left!=(N-1)) {
if ((size2[right]-size2[left])<=K) {
if (right<(N-1)) {
right++;
}
else {
break;
}
}
else {
if (max(ans2,(right-left)) > ans2) {
ans2 = max(ans2,(right-left));
}
left++;
}
maximum = max(ans1+ans2,maximum);
}
}
cout << maximum;
}