Header Ad

HackerEarth The maximum range problem solution

In this HackerEarth The maximum range problem solution You are given an array of size N and an integer K. Your task is to find the largest subarray of the provided array such that the absolute difference between any two elements in the subarray is less than or equal to K.

Let M and m be the maximum and minimum values in the selected largest subarray. Now, M - m <= k must hold.

Print the length of the largest subarray.


HackerEarth The maximum range problem solution


HackerEarth The maximum range problem solution.

#include<bits/stdc++.h>
using namespace std;
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize ("-ffloat-store")
#pragma GCC optimize ("-fno-defer-pop")
#define all(a) a.begin(),a.end()
#define ll long long int
#define ld long double
ll power(ll a,ll b,ll m){ if(b==0) return 1; if(b==1) return a%m; ll t=power(a,b/2,m)%m; t=(t*t)%m; if(b&1) t=((t%m)*(a%m))%m; return t;}
ll modInverse(ll a, ll m) { return power(a, m-2, m); }
#define ps push_back
#define fs first
#define sc second
#define takeline cin.ignore();
#define iactive cout.flush();
#define N 3000005
#define endl "\n"
#define mod 1000000007
int main(){
ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);

ll i,j,k,l,n;
cin>>n>>k;
ll ar[n+1];
for(i=1;i<=n;i++){
cin>>ar[i];
}
multiset<ll> st;
j=1; ll an=0;
for(i=1;i<=n;i++){
st.insert(ar[i]);
while((*(--st.end()))-(*st.begin())>k){
st.erase(st.lower_bound(ar[j]));
j++;
}
an=max(an,(ll)st.size());
}
cout<<an;
return 0;
}

Second solution

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e6 + 14;
int n, k, a[maxn];
multiset<int> s;
int main(){
ios::sync_with_stdio(0), cin.tie(0);
cin >> n >> k;
int ans = 0;
for(int i = 0, p = 0; i < n; i++){
cin >> a[i];
s.insert(a[i]);
while(*s.rbegin() - *s.begin() > k)
s.erase(s.find(a[p++]));
ans = max<int>(ans, s.size());
}
cout << ans << '\n';
}

Post a Comment

0 Comments