#include<bits/stdc++.h>
using namespace std;
const int maxn = 200010;
struct node
{
    int val,id;
    bool operator < (const node &A)const{
        return val==A.val?id<A.id:val>A.val;
    }
};
set<node>S;
int vis[maxn];
int fa[maxn],siz[maxn];
int ans[maxn];
int find(int x)
{
    if(x!=fa[x])
    fa[x] = find(fa[x]);
    return fa[x];
}
int unio(int a,int b)
{
    int va=find(a);
    int vb=find(b);
    if(va!=vb)
    {
        if(va<vb)
        {
            fa[vb] = va;
            siz[va]+=siz[vb];
            siz[vb] = 0;
            return siz[va];
        }
        else{
            fa[va] = vb;
            siz[vb]+=siz[va];
            siz[va] = 0;
            return siz[vb];
        }
    }
    return max(siz[va],siz[vb]);
}
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        int x;
        scanf("%d",&x);
        node a;
        a.id = i;
        a.val = x;
        S.insert(a);
    }
    set<node>::iterator it;
    memset(vis,0,sizeof(vis));
    memset(ans,0,sizeof(ans));
    for(int i=1;i<=n;i++)
    {
        fa[i] = i;
        siz[i] = 1;
    }
    int len = 0;
    for(it=S.begin();it!=S.end();it++)
    {
        int x = (*it).id;
        vis[x] = 1;
        int L=1,R=0,pre=x;
        for(int i=x-1;i>=1;i--)
        {
            if(vis[i]) L=unio(i,i+1),pre=i;
            else break;
        }
        for(int i=x+1;i<=n;i++)
        {
            if(vis[i])R=unio(pre,i);
            else break;
        }
        L = max(L,R);
       // cout<<L<<" asdsa \n";
        if(L>len)
        {
            for(int j=len+1;j<=L;j++){
                ans[j] = (*it).val;
            }
            len = L;
        }
        //if(len==n) break;
    }
    for(int i=1;i<=n;i++) printf("%d ",ans[i]);puts("");
}


#include<bits/stdc++.h>
using namespace std;
const int maxn = 200010;
struct node
{
    int val,id;
    bool operator < (const node &A)const{
        return val==A.val?id<A.id:val>A.val;
    }
};
set<node>S;
int vis[maxn];
int fa[maxn],siz[maxn];
int ans[maxn];
int find(int x)
{
    if(x!=fa[x])
    fa[x] = find(fa[x]);
    return fa[x];
}
int unio(int a,int b)
{
    int va=find(a);
    int vb=find(b);
    if(va!=vb)
    {
        if(va<vb)
        {
            fa[vb] = va;
            siz[va]+=siz[vb];
            siz[vb] = 0;
            return siz[va];
        }
        else{
            fa[va] = vb;
            siz[vb]+=siz[va];
            siz[va] = 0;
            return siz[vb];
        }
    }
    return max(siz[va],siz[vb]);
}
int main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        int x;
        cin>>x;
        node a;
        a.id = i;
        a.val = x;
        S.insert(a);
    }
    set<node>::iterator it;
    memset(vis,0,sizeof(vis));
    memset(ans,0,sizeof(ans));
    for(int i=1;i<=n;i++)
    {
        fa[i] = i;
        siz[i] = 1;
    }
    int len = 0;
    for(it=S.begin();it!=S.end();it++)
    {
        int x = (*it).id;
        vis[x] = 1;
        int L=1,R=0,pre=x;
        for(int i=x-1;i>=1;i--)
        {
            if(find(i)==find(pre)) break;
            if(vis[i]) L=unio(i,i+1),pre=i;
            else break;
        }
        for(int i=x+1;i<=n;i++)
        {
            if(find(i)==find(pre)) break;
            if(vis[i])R=unio(pre,i);
            else break;
        }
        L = max(L,R);
        if(L>len)
        {
            for(int j=len+1;j<=L;j++){
                ans[j] = (*it).val;
            }
            len = L;
        }
    }
    for(int i=1;i<=n;i++) printf("%d ",ans[i]);puts("");
}


#include <bits/stdc++.h>

#define pb push_back
#define mp make_pair
#define f first
#define s second
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define pi acos(-1.0)
#define EPS 1e-9
#define mem(n,x) memset(n,x,sizeof(n))
typedef long long ll;

using namespace std;

int arr[200005], ans[200005], n;
int table[200005][25];

void RMQ(){
	for(int i=0;i<n;++i){
		table[i][0]=arr[i];
	}
	for(int j=1;(1<<j)<=n;++j){
		for(int i=0;i+(1<<j)-1<n;++i){
			table[i][j]=min(table[i][j-1],table[i+(1<<(j-1))][j-1]);
		}
	}
}

int query(int i,int j){
	int k=log2(j-i+1);
	return min(table[i][k],table[j-(1<<k)+1][k]);
}

int getFurthest1(int ind){
	int low=ind+1, high=n-1, ret=-1;
	while(low<=high){
		int mid=(low+high)>>1;
		if(query(ind,mid)==arr[ind])
			ret=mid, low=mid+1;
		else
			high=mid-1;
	}
	return (ret==-1)?0:ret-ind;
}

int getFurthest2(int ind){
	int low=0, high=ind-1, ret=-1;
	while(low<=high){
		int mid=(low+high)>>1;
		if(query(mid,ind)==arr[ind])
			ret=mid, high=mid-1;
		else
			low=mid+1;
	}
	return (ret==-1)?0:ind-ret;
}

int main()
{
	scanf("%d",&n);
	for(int i=0;i<n;++i)
		scanf("%d",arr+i);

	RMQ();

	for(int i=0;i<n;++i){
		int x=1+getFurthest1(i)+getFurthest2(i);
		ans[x]=max(ans[x],arr[i]);
	}

	for(int i=n-1;i>=1;--i)
		ans[i]=max(ans[i],ans[i+1]);

	for(int i=1;i<=n;++i){
		printf("%d",ans[i]);
		if(i+1<=n)putchar(' ');
	}
	putchar('\n');

	return 0;
}


#include <bits/stdc++.h>

#define pb push_back
#define mp make_pair
#define f first
#define s second
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define pi acos(-1.0)
#define EPS 1e-9
#define mem(n,x) memset(n,x,sizeof(n))
typedef long long ll;

using namespace std;

int arr[200005], ans[200005], n;
int table[200005][25];

void RMQ(){
	for(int i=0;i<n;++i){
		table[i][0]=arr[i];
	}
	for(int j=1;(1<<j)<=n;++j){
		for(int i=0;i+(1<<j)-1<n;++i){
			table[i][j]=min(table[i][j-1],table[i+(1<<(j-1))][j-1]);
		}
	}
}

int query(int i,int j){
	int k=log2(j-i+1);
	return min(table[i][k],table[j-(1<<k)+1][k]);
}

int getFurthest1(int ind){
	int low=ind, high=n-1, ret=ind;
	while(low<=high){
		int mid=(low+high)>>1;
		if(query(ind,mid)==arr[ind])
			ret=mid, low=mid+1;
		else
			high=mid-1;
	}
	return ret-ind+1;
}

int getFurthest2(int ind){
	int low=0, high=ind, ret=ind;
	while(low<=high){
		int mid=(low+high)>>1;
		if(query(mid,ind)==arr[ind])
			ret=mid, high=mid-1;
		else
			low=mid+1;
	}
	return ind-ret+1;
}

int main()
{
	scanf("%d",&n);
	for(int i=0;i<n;++i)
		scanf("%d",arr+i);

	RMQ();

	for(int i=0;i<n;++i){
		int best=max(getFurthest1(i),getFurthest2(i));
		for(int j=1;j<=best;++j)ans[j]=max(ans[j],arr[i]);
	}

	for(int i=1;i<=n;++i){
		printf("%d",ans[i]);
		if(i+1<=n)putchar(' ');
	}
	putchar('\n');

	return 0;
}


#include <bits/stdc++.h>

#define pb push_back
#define mp make_pair
#define f first
#define s second
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define pi acos(-1.0)
#define EPS 1e-9
#define mem(n,x) memset(n,x,sizeof(n))
typedef long long ll;

using namespace std;

int arr[200005], ans[200005], n;
int table[200005][25];

void RMQ(){
	for(int i=0;i<n;++i){
		table[i][0]=arr[i];
	}
	for(int j=1;(1<<j)<=n;++j){
		for(int i=0;i+(1<<j)-1<n;++i){
			table[i][j]=min(table[i][j-1],table[i+(1<<(j-1))][j-1]);
		}
	}
}

int query(int i,int j){
	int k=log2(j-i+1);
	return min(table[i][k],table[j-(1<<k)+1][k]);
}

int getFurthest1(int ind){
	int low=ind, high=n-1, ret=ind;
	while(low<=high){
		int mid=(low+high)>>1;
		if(query(ind,mid)==arr[ind])
			ret=mid, low=mid+1;
		else
			high=mid-1;
	}
	return ret-ind+1;
}

int getFurthest2(int ind){
	int low=0, high=ind, ret=ind;
	while(low<=high){
		int mid=(low+high)>>1;
		if(query(mid,ind)==arr[ind])
			ret=mid, high=mid-1;
		else
			low=mid+1;
	}
	return ind-ret+1;
}

int main()
{
	scanf("%d",&n);
	for(int i=0;i<n;++i)
		scanf("%d",arr+i);

	RMQ();

	for(int i=0;i<n;++i){
		int best=max(getFurthest1(i),getFurthest2(i));
		ans[best]=max(ans[best],arr[i]);
	}

	for(int i=n-1;i>=1;--i)
		ans[i]=max(ans[i],ans[i+1]);

	for(int i=1;i<=n;++i){
		printf("%d",ans[i]);
		if(i+1<=n)putchar(' ');
	}
	putchar('\n');

	return 0;
}


#include<bits/stdc++.h>
using namespace std;

const int N = 2e5 + 6;
const int SN = 8e5 + 66;

#define LL long long int

int a[N], n, ba[N];
int tree[SN];
vector<int> ans;
int mini = INT_MAX;
int maxi = INT_MIN;
map<int, int> mm;
int l[N], r[N];
int irange[N];
int p[N], b[N];
vector<LL> va;

void KAMPSS(vector<LL> &v)
{
    map<LL, LL> JAJA;for(const LL &x: v) JAJA[x];
    LL k=1;for(auto &x: JAJA) x.second = k++; for(LL &x: v) x = JAJA[x];
}

void update(int idx, int l, int r, int ql, int qr, int val)
{
	if(l > qr or r < ql or l > r)return;
	if(l >= ql and r <= qr)
	{
		tree[idx] = val;
		return;
	}
	int mid = (l + r) / 2;
	update(idx + idx, l, mid, ql, qr, val);
	update(idx + idx + 1, mid + 1, r, ql, qr, val);

	tree[idx] = max(tree[idx + idx], tree[idx + idx + 1]);
}

void updatee(int idx, int l, int r, int ql, int qr, int val)
{
	if(l > qr or r < ql or l > r)return;
	if(l >= ql and r <= qr)
	{
		tree[idx] = val;
		return;
	}
	int mid = (l + r) / 2;
	updatee(idx + idx, l, mid, ql, qr, val);
	updatee(idx + idx + 1, mid + 1, r, ql, qr, val);

	tree[idx] = min(tree[idx + idx], tree[idx + idx + 1]);
}

int query(int idx, int l, int r, int ql, int qr)
{
	if(l > qr or r < ql or l > r)return -12;
	if(l >= ql and r <= qr)return tree[idx];
	int mid = (l + r) / 2;
	int x = query(idx + idx, l, mid, ql, qr);
	int y = query(idx + idx + 1, mid + 1, r, ql, qr);
	return max(x, y);
}

int queryy(int idx, int l, int r, int ql, int qr)
{
	if(l > qr or r < ql or l > r)return (n + 45);
	if(l >= ql and r <= qr)return tree[idx];
	int mid = (l + r) / 2;
	int x = queryy(idx + idx, l, mid, ql, qr);
	int y = queryy(idx + idx + 1, mid + 1, r, ql, qr);
	return min(x, y);
}

int main()
{
	cin >> n;

	for(int i = 1; i <= n; ++i)
	{
		cin >> a[i];
		ba[i] = a[i];
		va.push_back(a[i]);
	}

	KAMPSS(va);

	for(int i = 0; i < va.size(); i++)a[i + 1] = va[i];

	for(int i = 1; i <= n; i++)
	{
		mm[a[i]] = ba[i];
	}

	// solving for left.

	l[1] = 0;
	update(1, 1, n, a[1], a[1], 1);
	mini = a[1];

	for(int i = 1; i <= n; i++)
	{
		if(mini >= a[i])l[i] = 0;
		else
		{
			int get = query(1, 1, n, 1, a[i - 1]);
			l[i] = get;
		}
		update(1, 1, n, a[i], a[i], i);

		mini = min(mini, a[i]);
	}

	for(int i = 0; i < SN; i++)tree[i] = INT_MAX;

	r[n] = n + 1;
	updatee(1, 1, n, a[n], a[n], n);
	mini = a[n];

	for(int i = n; i > 0; --i)
	{
		if(mini >= a[i])r[i] = n + 1;
		else
		{
			int get = queryy(1, 1, n, 1, a[i - 1]);
			r[i] = get;
		}
		updatee(1, 1, n, a[i], a[i], i);

		mini = min(mini, a[i]);
	}

	for(int i = 1; i <= n; i++)
	{
		irange[i] = i - l[i] + r[i] - i;
		irange[i]--;
		p[a[i]] = max(p[a[i]], irange[i]);
		b[irange[i]] = max(b[irange[i]], a[i]);
	}

	ans.push_back(b[n]);
	int curIdx = n - 1;
	int curVal = b[n];
	while(curIdx > 0)
	{
		if(b[curIdx] == 0)ans.push_back(curVal);
		else
		{
			ans.push_back(b[curIdx]);
			curVal = b[curIdx];
		}
		curIdx--;
	}

	reverse(ans.begin(), ans.end());
	for(int i = 0; i < ans.size(); i++)cout << mm[ans[i]] << " ";
}


#include<bits/stdc++.h>
using namespace std;

const int N = 2e5 + 6;
const int SN = 8e5 + 66;

#define LL long long int

int a[N], n, ba[N];
int tree[SN];
vector<int> ans;
int mini = INT_MAX;
int maxi = INT_MIN;
map<int, int> mm;
int l[N], r[N];
int irange[N];
int p[N], b[N];
vector<LL> va;
int fa[N];

void KAMPSS(vector<LL> &v)
{
    map<LL, LL> JAJA;for(const LL &x: v) JAJA[x];
    LL k=1;for(auto &x: JAJA) x.second = k++; for(LL &x: v) x = JAJA[x];
}

void update(int idx, int l, int r, int ql, int qr, int val)
{
	if(l > qr or r < ql or l > r)return;
	if(l >= ql and r <= qr)
	{
		tree[idx] = val;
		return;
	}
	int mid = (l + r) / 2;
	update(idx + idx, l, mid, ql, qr, val);
	update(idx + idx + 1, mid + 1, r, ql, qr, val);

	tree[idx] = max(tree[idx + idx], tree[idx + idx + 1]);
}

void updatee(int idx, int l, int r, int ql, int qr, int val)
{
	if(l > qr or r < ql or l > r)return;
	if(l >= ql and r <= qr)
	{
		tree[idx] = val;
		return;
	}
	int mid = (l + r) / 2;
	updatee(idx + idx, l, mid, ql, qr, val);
	updatee(idx + idx + 1, mid + 1, r, ql, qr, val);

	tree[idx] = min(tree[idx + idx], tree[idx + idx + 1]);
}

int query(int idx, int l, int r, int ql, int qr)
{
	if(l > qr or r < ql or l > r)return -12;
	if(l >= ql and r <= qr)return tree[idx];
	int mid = (l + r) / 2;
	int x = query(idx + idx, l, mid, ql, qr);
	int y = query(idx + idx + 1, mid + 1, r, ql, qr);
	return max(x, y);
}

int queryy(int idx, int l, int r, int ql, int qr)
{
	if(l > qr or r < ql or l > r)return (n + 1);
	if(l >= ql and r <= qr)return tree[idx];
	int mid = (l + r) / 2;
	int x = queryy(idx + idx, l, mid, ql, qr);
	int y = queryy(idx + idx + 1, mid + 1, r, ql, qr);
	return min(x, y);
}

int main()
{
	cin >> n;

	for(int i = 1; i <= n; ++i)
	{
		cin >> a[i];
		ba[i] = a[i];
		va.push_back(a[i]);
	}

	KAMPSS(va);

	for(int i = 0; i < va.size(); i++)a[i + 1] = va[i];

	for(int i = 1; i <= n; i++)
	{
		mm[a[i]] = ba[i];
	}

	//for(int i = 1; i <= n; i++)cout << a[i] << " ";
	//cout << endl;

	// solving for left.

	l[1] = 0;
	update(1, 1, n, a[1], a[1], 1);
	mini = a[1];

	for(int i = 1; i <= n; i++)
	{
		if(mini >= a[i])l[i] = 0;
		else
		{
			int get = query(1, 1, n, 1, a[i] - 1);
			l[i] = get;
		}
		update(1, 1, n, a[i], a[i], i);

		mini = min(mini, a[i]);
	}

	for(int i = 0; i < SN; i++)tree[i] = INT_MAX;

	r[n] = n + 1;
	updatee(1, 1, n, a[n], a[n], n);
	mini = a[n];
	//cout << queryy(1, 1, n, 1, 1) << " ss\n";
	//cout << mm[a[n]] << " " << r[n] << " " << endl;

	for(int i = n - 1; i > 0; --i)
	{
		if(mini >= a[i])r[i] = n + 1;
		else
		{
			//cout << mm[a[i]] << " " << "here " << " " << a[i - 1] << " ";
			int get = queryy(1, 1, n, 1, a[i] - 1);
			r[i] = get;

		}//cout << mm[a[i]] << " " << r[i] << " " << endl;
		updatee(1, 1, n, a[i], a[i], i);

		mini = min(mini, a[i]);
	}//cout << endl;

	for(int i = 1; i <= n; i++)
	{
		//cout << a[i];
	}//cout << endl;

	for(int i = 1; i <= n; i++)
	{
		irange[i] = i - l[i] + r[i] - i;
		irange[i]--;
		//cout << l[i] << " " << r[i]  << " " << a[i] << endl;;
		p[a[i]] = max(p[a[i]], irange[i]);
		b[irange[i]] = max(b[irange[i]], a[i]);
	}//cout << endl;

	vector<int> anss;
	anss.push_back(b[n]);
	fa[n] = b[n];

	for(int i = n - 1; i > 0; --i)
	{
		if(b[i + 1] > b[i])b[i] = b[i + 1];
		anss.push_back(b[i]);
	}

	reverse(anss.begin(), anss.end());
	for(int i = 0; i < anss.size(); ++i)cout << mm[anss[i]] << " ";
}


#include<bits/stdc++.h>
using namespace std;

const int N = 2e5 + 6;
const int SN = 8e5 + 66;

#define LL long long int

int a[N], n, ba[N];
int tree[SN];
vector<int> ans;
int mini = INT_MAX;
int maxi = INT_MIN;
map<int, int> mm;
int l[N], r[N];
int irange[N];
int p[N], b[N];
vector<LL> va;

void KAMPSS(vector<LL> &v)
{
    map<LL, LL> JAJA;for(const LL &x: v) JAJA[x];
    LL k=1;for(auto &x: JAJA) x.second = k++; for(LL &x: v) x = JAJA[x];
}

void update(int idx, int l, int r, int ql, int qr, int val)
{
	if(l > qr or r < ql or l > r)return;
	if(l >= ql and r <= qr)
	{
		tree[idx] = val;
		return;
	}
	int mid = (l + r) / 2;
	update(idx + idx, l, mid, ql, qr, val);
	update(idx + idx + 1, mid + 1, r, ql, qr, val);

	tree[idx] = max(tree[idx + idx], tree[idx + idx + 1]);
}

void updatee(int idx, int l, int r, int ql, int qr, int val)
{
	if(l > qr or r < ql or l > r)return;
	if(l >= ql and r <= qr)
	{
		tree[idx] = val;
		return;
	}
	int mid = (l + r) / 2;
	updatee(idx + idx, l, mid, ql, qr, val);
	updatee(idx + idx + 1, mid + 1, r, ql, qr, val);

	tree[idx] = min(tree[idx + idx], tree[idx + idx + 1]);
}

int query(int idx, int l, int r, int ql, int qr)
{
	if(l > qr or r < ql or l > r)return -12;
	if(l >= ql and r <= qr)return tree[idx];
	int mid = (l + r) / 2;
	int x = query(idx + idx, l, mid, ql, qr);
	int y = query(idx + idx + 1, mid + 1, r, ql, qr);
	return max(x, y);
}

int queryy(int idx, int l, int r, int ql, int qr)
{
	if(l > qr or r < ql or l > r)return (n + 1);
	if(l >= ql and r <= qr)return tree[idx];
	int mid = (l + r) / 2;
	int x = queryy(idx + idx, l, mid, ql, qr);
	int y = queryy(idx + idx + 1, mid + 1, r, ql, qr);
	return min(x, y);
}

int main()
{
	cin >> n;

	for(int i = 1; i <= n; ++i)
	{
		cin >> a[i];
		ba[i] = a[i];
		va.push_back(a[i]);
	}

	KAMPSS(va);

	for(int i = 0; i < va.size(); i++)a[i + 1] = va[i];

	for(int i = 1; i <= n; i++)
	{
		mm[a[i]] = ba[i];
	}

	// solving for left.

	l[1] = 0;
	update(1, 1, n, a[1], a[1], 1);
	mini = a[1];

	for(int i = 1; i <= n; i++)
	{
		if(mini >= a[i])l[i] = 0;
		else
		{
			int get = query(1, 1, n, 1, a[i - 1]);
			l[i] = get;
		}
		update(1, 1, n, a[i], a[i], i);

		mini = min(mini, a[i]);
	}

	for(int i = 0; i < SN; i++)tree[i] = INT_MAX;

	r[n] = n + 1;
	updatee(1, 1, n, a[n], a[n], n);
	mini = a[n];

	for(int i = n; i > 0; --i)
	{
		if(mini >= a[i])r[i] = n + 1;
		else
		{
			int get = queryy(1, 1, n, 1, a[i - 1]);
			r[i] = get;
		}
		updatee(1, 1, n, a[i], a[i], i);

		mini = min(mini, a[i]);
	}

	for(int i = 1; i <= n; i++)
	{
		irange[i] = i - l[i] + r[i] - i;
		irange[i]--;
		p[a[i]] = max(p[a[i]], irange[i]);
		b[irange[i]] = max(b[irange[i]], a[i]);
	}

	ans.push_back(b[n]);
	int curIdx = n - 1;
	int curVal = b[n];
	while(curIdx > 0)
	{
		if(b[curIdx] == 0)ans.push_back(curVal);
		else
		{
			ans.push_back(b[curIdx]);
			curVal = b[curIdx];
		}
		curIdx--;
	}

	reverse(ans.begin(), ans.end());
	for(int i = 0; i < ans.size(); i++)cout << mm[ans[i]] << " ";
}


#include<bits/stdc++.h>
using namespace std;

const int N = 2e5 + 6;
const int SN = 8e5 + 66;

#define LL long long int

int a[N], n, ba[N];
int tree[SN];
vector<int> ans;
int mini = INT_MAX;
int maxi = INT_MIN;
map<int, int> mm;
int l[N], r[N];
int irange[N];
int p[N], b[N];
vector<LL> va;

void KAMPSS(vector<LL> &v)
{
    map<LL, LL> JAJA;for(const LL &x: v) JAJA[x];
    LL k=1;for(auto &x: JAJA) x.second = k++; for(LL &x: v) x = JAJA[x];
}

void update(int idx, int l, int r, int ql, int qr, int val)
{
	if(l > qr or r < ql or l > r)return;
	if(l >= ql and r <= qr)
	{
		tree[idx] = val;
		return;
	}
	int mid = (l + r) / 2;
	update(idx + idx, l, mid, ql, qr, val);
	update(idx + idx + 1, mid + 1, r, ql, qr, val);

	tree[idx] = max(tree[idx + idx], tree[idx + idx + 1]);
}

void updatee(int idx, int l, int r, int ql, int qr, int val)
{
	if(l > qr or r < ql or l > r)return;
	if(l >= ql and r <= qr)
	{
		tree[idx] = val;
		return;
	}
	int mid = (l + r) / 2;
	updatee(idx + idx, l, mid, ql, qr, val);
	updatee(idx + idx + 1, mid + 1, r, ql, qr, val);

	tree[idx] = min(tree[idx + idx], tree[idx + idx + 1]);
}

int query(int idx, int l, int r, int ql, int qr)
{
	if(l > qr or r < ql or l > r)return -12;
	if(l >= ql and r <= qr)return tree[idx];
	int mid = (l + r) / 2;
	int x = query(idx + idx, l, mid, ql, qr);
	int y = query(idx + idx + 1, mid + 1, r, ql, qr);
	return max(x, y);
}

int queryy(int idx, int l, int r, int ql, int qr)
{
	if(l > qr or r < ql or l > r)return (n + 1);
	if(l >= ql and r <= qr)return tree[idx];
	int mid = (l + r) / 2;
	int x = queryy(idx + idx, l, mid, ql, qr);
	int y = queryy(idx + idx + 1, mid + 1, r, ql, qr);
	return min(x, y);
}

int main()
{
	cin >> n;

	for(int i = 1; i <= n; ++i)
	{
		cin >> a[i];
		ba[i] = a[i];
		va.push_back(a[i]);
	}

	KAMPSS(va);

	for(int i = 0; i < va.size(); i++)a[i + 1] = va[i];

	for(int i = 1; i <= n; i++)
	{
		mm[a[i]] = ba[i];
	}

	// solving for left.

	l[1] = 0;
	update(1, 1, n, a[1], a[1], 1);
	mini = a[1];

	for(int i = 1; i <= n; i++)
	{
		if(mini >= a[i])l[i] = 0;
		else
		{
			int get = query(1, 1, n, 1, a[i] - 1);
			l[i] = get;
		}
		update(1, 1, n, a[i], a[i], i);

		mini = min(mini, a[i]);
	}

	for(int i = 0; i < SN; i++)tree[i] = INT_MAX;

	r[n] = n + 1;
	updatee(1, 1, n, a[n], a[n], n);
	mini = a[n];
	//cout << queryy(1, 1, n, 1, 1) << " ss\n";
	//cout << mm[a[n]] << " " << r[n] << " " << endl;

	for(int i = n - 1; i > 0; --i)
	{
		if(mini >= a[i])r[i] = n + 1;
		else
		{
			//cout << mm[a[i]] << " " << "here " << " " << a[i - 1] << " ";
			int get = queryy(1, 1, n, 1, a[i] - 1);
			r[i] = get;

		}//cout << mm[a[i]] << " " << r[i] << " " << endl;
		updatee(1, 1, n, a[i], a[i], i);

		mini = min(mini, a[i]);
	}//cout << endl;

	for(int i = 1; i <= n; i++)
	{
		//cout << a[i];
	}//cout << endl;

	for(int i = 1; i <= n; i++)
	{
		irange[i] = i - l[i] + r[i] - i;
		irange[i]--;
		//cout << l[i] << " " << r[i]  << " " << a[i] << endl;;
		p[a[i]] = max(p[a[i]], irange[i]);
		b[irange[i]] = max(b[irange[i]], a[i]);
	}//cout << endl;

	for(int i = 1; i <= n; i++)
	{
		//cout << p[a[i]] << " ";
	}//cout << endl;

	ans.push_back(b[n]);
	int curIdx = n - 1;
	int curVal = b[n];
	while(curIdx > 0)
	{
		if(b[curIdx] == 0)ans.push_back(curVal);
		else
		{
			ans.push_back(b[curIdx]);
			curVal = b[curIdx];
		}
		curIdx--;
	}

	reverse(ans.begin(), ans.end());
	for(int i = 0; i < ans.size(); i++)cout << mm[ans[i]] << " ";
}


#include <iostream>
#include <algorithm>
#include <stack>
#include <string.h>
using namespace std;

const int mx = 2e5+10;

int ans[mx], l[mx], r[mx], a[mx];
stack<int> stk;
int n, tmp = 0;

int main() {
    cin >> n;
    fill(r, r + n + 1, n);
    memset(l, -1, sizeof(l));
    for (int i = 0; i < n; i++) cin >> a[i];

    for (int i = 0; i < n; i++){
        while(!stk.empty() && a[stk.top()] >= a[i]) stk.pop();
        if (!stk.empty()) l[i] = stk.top();
        stk.push(i);
    }

    while (!stk.empty()) stk.pop();
    for (int i = n - 1; i >= 0; i--){
        while (!stk.empty() && a[stk.top()] >= a[i]) stk.pop();
        if (!stk.empty()) r[i] = stk.top();
        stk.push(i);
    }

    for (int i = 0; i < n; i++){
        int len = r[i] - l[i] - 1;
        ans[len] = max(ans[len], a[i]);
    }

    for (int i = n ; i > 0; i--) ans[i] = max(ans[i], ans[i + 1]);
    for (int i = 1; i <= n; i++) cout << ans[i] << " ";
    return 0;
}


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

const int mx = 2e5+10;

int ans[mx], l[mx], r[mx], a[mx];
stack<int> stk;
int n, tmp = 0;

int main() {
    cin >> n;
    fill(r, r + n + 1, n);
    memset(l, -1, sizeof(l));
    for (int i = 0; i < n; i++) cin >> a[i];

    for (int i = 0; i < n; i++){
        while(!stk.empty() && a[stk.top()] >= a[i]) stk.pop();
        if (!stk.empty()) l[i] = stk.top();
        stk.push(i);
    }

    while (!stk.empty()) stk.pop();
    for (int i = n - 1; i >= 0; i--){
        while (!stk.empty() && a[stk.top()] >= a[i]) stk.pop();
        if (!stk.empty()) r[i] = stk.top();
        stk.push(i);
    }

    for (int i = 0; i < n; i++){
        int len = r[i] - l[i] - 1;
        ans[len] = max(ans[len], a[i]);
    }

    for (int i = n ; i > 0; i--) ans[i] = max(ans[i], ans[i + 1]);
    for (int i = 1; i <= n; i++) cout << ans[i] << " ";
    return 0;
}


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

const int mx = 2e5+10;

int ans[mx], l[mx], r[mx], a[mx];
stack<int> stk;
int n, tmp = 0;

int main() {
    cin >> n;
    fill(r, r + n + 1, n);
    memset(l, -1, sizeof(l));
    for (int i = 0; i < n; i++) cin >> a[i];

    for (int i = 0; i < n; i++){
        while(!stk.empty() && a[stk.top()] >= a[i]) stk.pop();
        if (!stk.empty()) l[i] = stk.top();
        stk.push(i);
    }

    while (!stk.empty()) stk.pop();
    for (int i = n - 1; i >= 0; i--){
        while (!stk.empty() && a[stk.top()] >= a[i]) stk.pop();
        if (!stk.empty()) r[i] = stk.top();
        stk.push(i);
    }

    for (int i = 0; i < n; i++){
        int len = r[i] - l[i] - 1;
        ans[len] = max(ans[len], a[i]);
    }

    for (int i = n ; i > 0; i--) ans[i] = max(ans[i], ans[i + 1]);
    for (int i = 1; i <= n; i++) cout << ans[i] << " ";
    return 0;
}


#include <bits/stdc++.h>
#define sz              size()
#define pb              push_back
#define Fr              first
#define Sc              second
#define int             ll
#define Log2(x)         31^__builtin_clz(x)
using namespace std;
typedef long long ll;
int n, B[400400];
pair<int, int> C[400400];
int ans[400400];
struct SparseTable{
  int n, *A, M[400400][Log2(400400)+1];
  void build(int *_A, int _n){ A=_A, n=_n;
    for(int i=0 ; i<n ; i++) M[i][0]=i;
    for(int j=1 ; (1<<j) <= n ; j++)
      for(int i=0 ; i+(1<<j)-1<n ; i++)
        M[i][j] = A[M[i][j-1]] <= A[M[i+(1<<j-1)][j-1]] ? M[i][j-1] : M[i+(1<<j-1)][j-1];
  }
  int inline rmnq(int l, int r){
    int k = Log2(r-l+1);
    return A[M[l][k]] <= A[M[r-(1<<k)+1][k]] ? M[l][k] : M[r-(1<<k)+1][k];
  }
}St;
int leftBinary(int R, int val) {
    int l = 0, r = R;
    int len = 0;
    while(l <= r) {
        int mid = l + r >> 1LL;
        if(B[St.rmnq(mid, R)] == val) {
            len = mid;
            r = mid - 1;
        } else l = mid + 1;
    }
    return abs(len - R);
}
int rightBinary(int l, int val) {
    int r = n - 1, L = l;
    int len = 0;
    while(l <= r) {
        int mid = l + r >> 1LL;
        if(B[St.rmnq(L, mid)] == val) {
            len = mid;
            l = mid + 1;
        } else r = mid - 1;
    }
    return abs(len - L);
}
int32_t main() {

    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    cin >> n;
    for(int i = 0 ; i < n ; i++) {
        cin >> C[i].Fr;
        C[i].Sc = -i;
        B[i] = C[i].Fr;
    }
    St.build(B, n);
    sort(C, C + n);
    reverse(C, C + n);
    int now = 0;
    for(int i = 0 ; i < n ; i++) {
        int len = rightBinary(-1 * C[i].Sc, C[i].Fr) + leftBinary(-1 * C[i].Sc, C[i].Fr);
        while(now <= len)
            ans[now++] = C[i].Fr;
    }
    for(int i = 0 ; i < n ; i++) cout << ans[i] << " ";
    cout << endl;
}


#include <bits/stdc++.h>
#define sz              size()
#define pb              push_back
#define Fr              first
#define Sc              second
#define int             ll
using namespace std;
typedef long long ll;
int n, B[400400];
stack<int> st;
pair<int, int> C[400400];
int ans[400400];

int32_t main() {

    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    cin >> n;
    for(int i = 0 ; i < n ; i++) {
        cin >> C[i].Fr;
        B[i] = C[i].Fr;
    }
    for(int i = 0 ; i < n ; i++) {
        while(!st.empty() && B[st.top()] > B[i]) {
            C[st.top()].Sc = i - st.top();
            st.pop();
        }
        st.push(i);
    }
    while(!st.empty()) {
        C[st.top()].Sc = n - st.top();
        st.pop();
    }
    for(int i = n - 1 ; i > -1 ; i--) {
        while(!st.empty() && B[st.top()] > B[i]) {
            C[st.top()].Sc += st.top() - i - 1;
            st.pop();
        }
        st.push(i);
    }
    while(!st.empty()) {
        C[st.top()].Sc += st.top();
        st.pop();
    }
    sort(C, C + n);
    reverse(C, C + n);
    for(int i = 0, now = 0 ; i < n ; i++) {
        while(now < C[i].Sc)
            ans[now++] = C[i].Fr;
    }
    for(int i = 0 ; i < n ; i++) cout << ans[i] << " ";
    cout << endl;
}


#include <bits/stdc++.h>
#define sz              size()
#define pb              push_back
#define Fr              first
#define Sc              second
#define int             ll
#define Log2(x)         31^__builtin_clz(x)
using namespace std;
typedef long long ll;
int n, B[200200];
pair<int, int> C[200200];
int ans[200200];
struct SparseTable{
  int n, *A, M[200200][Log2(200200)+1];
  void build(int *_A, int _n){ A=_A, n=_n;
    for(int i=0 ; i<n ; i++) M[i][0]=i;
    for(int j=1 ; (1<<j) <= n ; j++)
      for(int i=0 ; i+(1<<j)-1<n ; i++)
        M[i][j] = A[M[i][j-1]] <= A[M[i+(1<<j-1)][j-1]] ? M[i][j-1] : M[i+(1<<j-1)][j-1];
  }
  int inline rmnq(int l, int r){
    int k = Log2(r-l+1);
    return A[M[l][k]] <= A[M[r-(1<<k)+1][k]] ? M[l][k] : M[r-(1<<k)+1][k];
  }
}St;
int leftBinary(int R, int val) {
    int l = 0, r = R;
    int len = 0;
    while(l <= r) {
        int mid = l + r >> 1LL;
        if(B[St.rmnq(mid, R)] == val) {
            len = mid;
            r = mid - 1;
        } else l = mid + 1;
    }
    return abs(len - R);
}
int rightBinary(int l, int val) {
    int r = n - 1, L = l;
    int len = 0;
    while(l <= r) {
        int mid = l + r >> 1LL;
        if(B[St.rmnq(L, mid)] == val) {
            len = mid;
            l = mid + 1;
        } else r = mid - 1;
    }
    return abs(len - L);
}
int32_t main() {

    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    cin >> n;
    for(int i = 0 ; i < n ; i++) {
        cin >> C[i].Fr;
        C[i].Sc = -i;
        B[i] = C[i].Fr;
    }
    St.build(B, n);
    sort(C, C + n);
    reverse(C, C + n);
    int now = 0;
    for(int i = 0 ; i < n ; i++) {
        int len = rightBinary(-1 * C[i].Sc, C[i].Fr) + leftBinary(-1 * C[i].Sc, C[i].Fr);
        while(now <= len)
            ans[now++] = C[i].Fr;
    }
    for(int i = 0 ; i < n ; i++) cout << ans[i] << " ";
    cout << endl;
}


#include <bits/stdc++.h>
#define sz              size()
#define pb              push_back
#define Fr              first
#define Sc              second
#define int             ll
#define Log2(x)         31^__builtin_clz(x)
using namespace std;
typedef long long ll;
int n, B[400400];
pair<int, int> C[400400];
int ans[400400];
struct SparseTable{
  int n, *A, M[400400][25];
  void build(int *_A, int _n){ A=_A, n=_n;
    for(int i=0 ; i<n ; i++) M[i][0]=i;
    for(int j=1 ; (1<<j) <= n ; j++)
      for(int i=0 ; i+(1<<j)-1<n ; i++)
        M[i][j] = A[M[i][j-1]] <= A[M[i+(1<<j-1)][j-1]] ? M[i][j-1] : M[i+(1<<j-1)][j-1];
  }
  int inline rmnq(int l, int r){
    int k = Log2(r-l+1);
    return A[M[l][k]] <= A[M[r-(1<<k)+1][k]] ? M[l][k] : M[r-(1<<k)+1][k];
  }
}St;
int leftBinary(int R, int val) {
    int l = 0, r = R;
    int len = 0;
    while(l <= r) {
        int mid = l + r >> 1LL;
        if(B[St.rmnq(mid, R)] == val) {
            len = mid;
            r = mid - 1;
        } else l = mid + 1;
    }
    return abs(len - R);
}
int rightBinary(int l, int val) {
    int r = n - 1, L = l;
    int len = 0;
    while(l <= r) {
        int mid = l + r >> 1LL;
        if(B[St.rmnq(L, mid)] == val) {
            len = mid;
            l = mid + 1;
        } else r = mid - 1;
    }
    return abs(len - L);
}
int32_t main() {

    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    cin >> n;
    for(int i = 0 ; i < n ; i++) {
        cin >> C[i].Fr;
        C[i].Sc = -i;
        B[i] = C[i].Fr;
    }
    St.build(B, n);
    sort(C, C + n);
    reverse(C, C + n);
    int now = 0;
    for(int i = 0 ; i < n ; i++) {
        int len = rightBinary(-1 * C[i].Sc, C[i].Fr) + leftBinary(-1 * C[i].Sc, C[i].Fr);
        while(now <= len)
            ans[now++] = C[i].Fr;
    }
    for(int i = 0 ; i < n ; i++) cout << ans[i] << " ";
    cout << endl;
}


#include <bits/stdc++.h>
#define sz              size()
#define pb              push_back
#define Fr              first
#define Sc              second
#define int             ll
#define Log2(x)         31^__builtin_clz(x)
using namespace std;
typedef long long ll;
int n, B[400400 << 2LL];
pair<int, int> C[400400 << 2LL];
int ans[400400 << 2LL];
struct SparseTable{
  int n, *A, M[400400 << 2LL][Log2(400400 << 2LL)+1];
  void build(int *_A, int _n){ A=_A, n=_n;
    for(int i=0 ; i<n ; i++) M[i][0]=i;
    for(int j=1 ; (1<<j) <= n ; j++)
      for(int i=0 ; i+(1<<j)-1<n ; i++)
        M[i][j] = A[M[i][j-1]] <= A[M[i+(1<<j-1)][j-1]] ? M[i][j-1] : M[i+(1<<j-1)][j-1];
  }
  int inline rmnq(int l, int r){
    int k = Log2(r-l+1);
    return A[M[l][k]] <= A[M[r-(1<<k)+1][k]] ? M[l][k] : M[r-(1<<k)+1][k];
  }
}St;
int leftBinary(int R, int val) {
    int l = 0, r = R;
    int len = 0;
    while(l <= r) {
        int mid = l + r >> 1LL;
        if(B[St.rmnq(mid, R)] == val) {
            len = mid;
            r = mid - 1;
        } else l = mid + 1;
    }
    return abs(len - R);
}
int rightBinary(int l, int val) {
    int r = n - 1, L = l;
    int len = 0;
    while(l <= r) {
        int mid = l + r >> 1LL;
        if(B[St.rmnq(L, mid)] == val) {
            len = mid;
            l = mid + 1;
        } else r = mid - 1;
    }
    return abs(len - L);
}
int32_t main() {

    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    cin >> n;
    for(int i = 0 ; i < n ; i++) {
        cin >> C[i].Fr;
        C[i].Sc = -i;
        B[i] = C[i].Fr;
    }
    St.build(B, n);
    sort(C, C + n);
    reverse(C, C + n);
    int now = 0;
    for(int i = 0 ; i < n ; i++) {
        int len = rightBinary(-1 * C[i].Sc, C[i].Fr) + leftBinary(-1 * C[i].Sc, C[i].Fr);
        while(now <= len)
            ans[now++] = C[i].Fr;
    }
    for(int i = 0 ; i < n ; i++) cout << ans[i] << " ";
    cout << endl;
}


#include <bits/stdc++.h>
#define sz              size()
#define pb              push_back
#define Fr              first
#define Sc              second
using namespace std;
typedef long long ll;
int n, B[400400];
stack<int> st;
pair<int, int> C[400400];
int ans[400400];
int32_t main() {

    scanf("%i", &n);
    for(int i = 0 ; i < n ; i++) {
        scanf("%i", &C[i].Fr);
        B[i] = C[i].Fr;
    }
    for(int i = 0 ; i < n ; i++) {
        while(!st.empty() && B[st.top()] > B[i]) {
            C[st.top()].Sc = i - st.top();
            st.pop();
        }
        st.push(i);
    }
    while(!st.empty()) {
        C[st.top()].Sc = n - st.top();
        st.pop();
    }
    for(int i = n - 1 ; i > -1 ; i--) {
        while(!st.empty() && B[st.top()] > B[i]) {
            C[st.top()].Sc += st.top() - i - 1;
            st.pop();
        }
        st.push(i);
    }
    while(!st.empty()) {
        C[st.top()].Sc += st.top();
        st.pop();
    }
    sort(C, C + n, greater<pair<int, int> >());
    for(int i = 0, now = 0 ; i < n ; i++) {
        while(now < C[i].Sc)
            ans[now++] = C[i].Fr;
    }
    for(int i = 0 ; i < n ; i++) printf("%i ", ans[i]);
    printf("\n");
}


#include <bits/stdc++.h>
#define sz              size()
#define pb              push_back
#define Fr              first
#define Sc              second
#define int             ll
#define Log2(x)         31^__builtin_clz(x)
using namespace std;
typedef long long ll;
int n, B[200200];
pair<int, int> C[200200];
int ans[200200];
struct SparseTable{
  int n, *A, M[200200][Log2(200200)+1];
  void build(int *_A, int _n){ A=_A, n=_n;
    for(int i=0 ; i<n ; i++) M[i][0]=i;
    for(int j=1 ; (1<<j) <= n ; j++)
      for(int i=0 ; i+(1<<j)-1<n ; i++)
        M[i][j] = A[M[i][j-1]] <= A[M[i+(1<<j-1)][j-1]] ? M[i][j-1] : M[i+(1<<j-1)][j-1];
  }
  int inline rmnq(int l, int r){
    int k = Log2(r-l+1);
    return A[M[l][k]] <= A[M[r-(1<<k)+1][k]] ? M[l][k] : M[r-(1<<k)+1][k];
  }
}St;
int leftBinary(int R, int val) {
    int l = 0, r = R;
    int len = 0;
    while(l <= r) {
        int mid = l + r >> 1LL;
        if(B[St.rmnq(mid, R)] == val) {
            len = mid;
            r = mid - 1;
        } else l = mid + 1;
    }
    return abs(len - R);
}
int rightBinary(int l, int val) {
    int r = n - 1, L = l;
    int len = 0;
    while(l <= r) {
        int mid = l + r >> 1LL;
        if(B[St.rmnq(L, mid)] == val) {
            len = mid;
            l = mid + 1;
        } else r = mid - 1;
    }
    return abs(len - L);
}
int32_t main() {

    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    cin >> n;
    for(int i = 0 ; i < n ; i++) {
        cin >> C[i].Fr;
        C[i].Sc = -i;
        B[i] = C[i].Fr;
    }
    St.build(B, n);
    sort(C, C + n);
    reverse(C, C + n);
    int now = 0;
    for(int i = 0 ; i < n ; i++) {
        int len = rightBinary(-1 * C[i].Sc, C[i].Fr) + leftBinary(-1 * C[i].Sc, C[i].Fr);
        while(now <= len + t)
            ans[now++] = C[i].Fr;
    }
    for(int i = 0 ; i < n ; i++) cout << ans[i] << " ";
    cout << endl;
}


import sys
import math
n,d= map(int,sys.stdin.readline().split())
s=input()
s=(s.split())
for i in range(n):
    s[i]=int(s[i])
max=n
total=0
boolean=0
for j in range(0,n-1):
    if s[n-1-j]<=(s[0]+d):
        max=n-1-j
        total=total+((max-1)*(max)*(max+1))//6
        if total!=0:
            boolean=1
        break
if boolean==1:
    for i in range(1,n-max):
        for j in (max+i,n):
            if s[n-1+max+i-j]<=s[i]+d:
                m=n-1+max+i-j
                total=total+(m-i-1)*(m-i)//2
                break
if boolean==0:
    max=0
    total=0
    for i in range(n-2):
        for j in range(i+1,n):
            if s[j]<=s[i]+d:
                max=j
                total=total+max-i-1
print(total)


import bisect

N, D = map(int, input().split())

A = list(map(int, input().split()))
A.sort()

ans = 0
for i in range(N):
    X = bisect.bisect_left(A, A[i] - D)
    temp = i - X
    ans += max(0, (temp * (temp - 1))//2)
print(ans)


from collections import Counter,defaultdict,deque
#import heapq as hq
#from itertools import count, islice
#from functools import reduce
#alph = 'abcdefghijklmnopqrstuvwxyz'
#from math import factorial as fact
#a,b = [int(x) for x in input().split()]
import math
import sys

input=sys.stdin.readline
n,d = [int(x) for x in input().split()]
arr = [int(x) for x in input().split()]
window = deque()
res = 0
for el in arr:
    window.append(el)
    while len(window)>=1 and (window[-1]-window[0])>d:
        window.popleft()
    #print(window)
    l = len(window)
    res+=(l-2)*(l-1)//2
print(res)


def f(a,j,d):
    l=j
    r=len(a)
    while(r-l>1):
        m=(r+l)//2
        if(a[m]>d):
            r=m
        elif(a[m]<d):
            l=i
        else:
            return (m+1)-j-1
    return r-j-1

n,d=map(int,input().split())
a=list(map(int,input().split()))
ans=0
for i in range(n):
    x=f(a,i,a[i]+d)
    if x>1:
        ans+=((x)*(x-1))//2
print(ans)


def f(a,j,d):
    l=j
    r=len(a)
    while(r-l>1):
        m=(r+l)//2
        if(a[m]>d):
            r=m
        elif(a[m]<d):
            l=m
        else:
            return (m+1)-j-1
    return r-j-1

n,d=map(int,input().split())
a=list(map(int,input().split()))
ans=0
for i in range(n):
    x=f(a,i,a[i]+d)
    ans+=((x)*(x-1))//2
print(ans)


def points_on_line(l,d):
  j=0
  combination=0
  for i in range(len(l)):
    while j<len(l) and l[j]<=l[i]+d:
      j+=1
    nums=j-i-1
    combination+=nums*(nums-1)//2
  return combination

n,d=[int(x) for x in input().split()]
l=[int(x) for x in input().split()]
print (points_on_line(l,d))


n, d = map(int, input().split())
l = list(map(int, input().split()))
j = 0
s = 0
for i in range(2, n):
    while l[i] - l[j] > d:
        j += 1
    k = i-j
    s += k*(k-1)//2
print(s)


n,d=map(int,input().split())
l1=list(map(int,input().split()))
ans=0
for i in range(0,n-1):
    j=i+1
    c=0
    while j <n and l1[j]-l1[i] <=d:
        c+=1
        j+=1
    ans+= ( c*(c-1))//2
print(ans)


n,d=map(int,input().split())
l1=list(map(int,input().split()))
ans=0
j=0
for i in range(0,n-1):
    j=max(j,i+1)
    while j <n and l1[j]-l1[i] <=d:
        j+=1
    j-=1
    ans+= ( (j-i)*((j-i-1)) )//2
print(ans)


n,d=map(int,input().split())
c=list(map(int,input().split()))
x=0;t=0
for i in range(n-2):
    while (t<n and c[t]<=c[i]+d):
        t=t+1
    t-i-1
    x=x+(t-i-1)*(t-i-2)/2
print(int(x))


def numbersListInput():
    aux = list(map(int,input().strip().split()))
    return aux

def find_tail(arr, n, maxVal):
    # binary search to find biggest number smaller than maxVal
    mini = 0
    maxi = n
    mid = int(n/2)
    while True:
        if mid == 0 or mid == n-1:
            return mid
        if arr[mid] == maxVal:
            return mid
        if arr[mid] > maxVal and arr[mid-1] < maxVal:
            return mid-1
        if arr[mid] > maxVal and arr[mid-1] > maxVal:
            maxi = mid
            mid = int((mini+maxi)/2)
        if arr[mid] < maxVal and arr[mid-1] < maxVal:
            mini = mid
            mid = int((mini+maxi)/2)

# input
usr_input = numbersListInput()
n = int(usr_input[0])
d = int(usr_input[1])
numbersList = numbersListInput()

# process
res = 0
tail =0
for head in range(n):
    #tail = find_tail(numbersList, n, d)
    while (numbersList[head] - numbersList[tail] > d):
        tail += 1
    res += int(((head-tail)*(head-tail-1))/2)

# print answer
print(res)


def numbersListInput():
    aux = list(map(int,input().strip().split()))
    return aux

def find_tail(arr, n, maxVal):
    # binary search to find biggest number smaller than maxVal
    mini = 0
    maxi = n
    mid = int(n/2)
    while True:
        if mid == 0 or mid == n-1:
            return mid
        if arr[mid] == maxVal:
            return mid
        if arr[mid] > maxVal and arr[mid-1] < maxVal:
            return mid-1
        if arr[mid] > maxVal and arr[mid-1] > maxVal:
            maxi = mid
            mid = int((mini+maxi)/2)
        if arr[mid] < maxVal and arr[mid-1] < maxVal:
            mini = mid
            mid = int((mini+maxi)/2)

# input
usr_input = numbersListInput()
n = int(usr_input[0])
d = int(usr_input[1])
numbersList = numbersListInput()

# process
res = 0
head = 0
for i in range(n):
    j = 0
    while (numbersList[i] - numbersList[j] > d):
        j += 1
    res += int(((i-j)*(i-j-1))/2)

# print answer
print(res)


from collections import deque

n,m = [int(i) for i in input().split()]
list_inp = input().split()
list_work = []
for i in range(n-1):
    list_work.append(int(list_inp[i+1])-int(list_inp[i]))
D = deque()
ways=0
for i in range(n-1):
    while sum(D)+list_work[i]>m and len(D)>0:
        D.popleft()
    if sum(D)+list_work[i] <= m:
        ways += int(len(D)*(len(D)+1)/2)
        D.append(list_work[i])
print (ways)


n,m=[int(i) for i in input().split()]
list_inp=input().split()
list_work=[]
for i in range(n):
    list_work.append(int(list_inp[i]))
way_sum=0
for i in range(len(list_work)-2):
    j=2
    while list_work[i]+m>=list_work[i+j]:
        way_sum+=int(j-1)
        j+=1
        if i+j>=len(list_work):break
print(way_sum)


from collections import deque

n,m = [int(i) for i in input().split()]
list_inp = input().split()

D = deque()
ways=0
Sum=0

for i in range(n-1):
    while Sum+int(list_inp[i+1])-int(list_inp[i])>m and len(D)>0:
        Sum -= D.popleft()

    if Sum+int(list_inp[i+1])-int(list_inp[i]) <= m:
        ways += int(len(D)*(len(D)+1)/2)
        D.append(int(list_inp[i+1])-int(list_inp[i]))
        Sum += D[-1]

print (ways)


from collections import deque

n,m = [int(i) for i in input().split()]
list_inp = input().split()
D = deque()
ways=0
for i in range(n-1):
    while sum(D)+int(list_inp[i+1])-int(list_inp[i])>m and len(D)>0:
        D.popleft()
    if sum(D)+int(list_inp[i+1])-int(list_inp[i]) <= m:
        ways += int(len(D)*(len(D)+1)/2)
        D.append(int(list_inp[i+1])-int(list_inp[i]))
print (ways)


from collections import deque

n,m = [int(i) for i in input().split()]
list_inp = input().split()

D = deque()
ways=0

#D用来储存相邻两个数之间的差值，ways用于统计可行的数量

for i in range(n-1):
    while sum(D)+int(list_inp[i+1])-int(list_inp[i])>m and len(D)>0:
        D.popleft()

#当D值总和即将超过m时，移除最开始的差值，直至符合要求或队列为空

    if sum(D)+int(list_inp[i+1])-int(list_inp[i]) <= m:
        ways += int(len(D)*(len(D)+1)/2)

#根据数学计算，每次进入一个差值时，共有如上组点符合要求

        D.append(int(list_inp[i+1])-int(list_inp[i]))

#再将上次的差值传入

print (ways)


n,d=[int(i) for i in input().split()]
x=[int(i) for i in input().split()]

k=0
S=0

for i in range(2,n):
    while x[i]-x[k]>d:k=k+1
    P=i-k
    S+=P*(P-1)//2

print(S)


a=input()
n=int(a.split()[0])
d=int(a.split()[1])
b=input()
l=[]
for j in range(n):
    l.append(int(b.split()[j]))
x=0
if l[0]+d>l[-1]:
    print(0)
else:
    while len(l)!=3:
        k=0
        while l[0]+d>l[k]:
            k+=1
        x=int(x+k*(k-1)/2)
        l.remove(l[0])
    else:
        if l[2]-l[0]<=d:
            x=x+1

    print(x)


from collections import deque
n,d=[int(i) for i in input().split()]
x=[int(i) for i in input().split()]
ans=0
D=deque()
while True:
    for i in range(n):
        if len(D)==0 or x[i]-D[0]<=d:
            D.append(x[i])
            if len(D)>=3:
                ans+=(len(D)-1)*(len(D)-2)//2
    D.popleft()
    if x[n-1] in D:
        break
print(ans)


n,d=[int(i) for i in input().split()]
x=[int(i) for i in input().split()]
ans=0
for i in range(n):
    for j in range(i+1,n):
        if x[j]-x[i]<=d:
            ans+=j-i-1
        else:
            break
print(ans)


from collections import deque
n,d=[int(i) for i in input().split()]
x=[int(i) for i in input().split()]
ans=0
D=deque()
for i in range(n):
    D.append(x[i])
    if x[i]-D[0]<=d and len(D)>=3:
        ans+=(len(D)-1)*(len(D)-2)//2
    elif x[i]-D[0]>d:
        D.popleft()
print(ans)


from collections import deque
n,d=[int(i) for i in input().split()]
x=[int(i) for i in input().split()]
ans=0
D=deque()
for i in range(n):
    D.append(x[i])
    if x[i]-D[0]>d:
        D.popleft()
    if x[i]-D[0]<=d and len(D)>=3:
        ans+=(len(D)-1)*(len(D)-2)//2
print(ans)


from collections import deque
n,d=[int(i) for i in input().split()]
x=[int(i) for i in input().split()]
ans=0
D=deque()
for i in range(n):
    D.append(x[i])
    if D[-1]-D[0]<=d and len(D)>=3:
        ans+=(len(D)-1)*(len(D)-2)//2
    while D[-1]-D[0]>d:
        D.popleft()
        if D[-1]-D[0]<=d:
            ans+=(len(D)-1)*(len(D)-2)//2
    #print('i',i)
    #print('D',D)
    #print('ans',ans)
print(ans)


from bisect import bisect_left

def ncr(n):
    return n*(n-1)*(n-2)//6

n,d = map(int,input().split())
a=list(map(int,input().split()))
res=0
for i in range(n-2):
    j=bisect_left(a,a[i]+d,lo=i)
    # print(i,j)
    if j<len(a) and a[j]-a[i]<=d:
        res+=ncr(j-i+1)
print(res)


from bisect import bisect_right

n,d = map(int,input().split())
a=list(map(int,input().split()))
res=0
for i in range(n-2):
    j=bisect_right(a,a[i]+d)
    k=j-i
    res+=(k-1)*(k-2)//2
print(res)


from bisect import bisect_left

def ncr(n):
    return n*(n-1)*(n-2)//6

n,d = map(int,input().split())
a=list(map(int,input().split()))
res=0
j=2
for i in range(n-2):
    if j>=len(a):
        continue
    while(j<len(a) and a[j]-a[i]<=d):
        j+=1
    res+=ncr(j-i)
print(res)


n,d = map(int,input().split())
A = list(map(int,input().split()))
A.sort()
i = 0
res = 0
for j in range(2,n):

    while (i+2<=j):
        if A[j]-A[i]>d:
            i+=1
        else:
            res += (j-i)*(j-i-1)//2
            break
print(res)


def f(n):
    if n>1:
        return n*f(n-1)
    else:
        return 1
from collections import deque
d=deque()
s1=input()
s2=s1.split()
n=int(s2[0])
l=int(s2[1])
s3=input()
s5=s3.split()
s4=[]
for i in range (n):
    s4.append(int(s5[i]))
suma=0
j=3
i=0
if n>=3:
    d.append(s4[0])
    d.append(s4[1])
    d.append(s4[2])
    while j!=n:
        if d[-1]-d[0]<=l:
            if len(d)==3:
                suma+=1
            elif len(d)>3:
                x=len(d)-1
                y=x-2
                x=f(x)
                y=2*f(y)
                suma+=int(x/y)
            d.append(s4[j])
            j+=1
        if  d[-1]-d[0]>l and len(d)>3:
            d.popleft()
        elif d[-1]-d[0]>l and len(d)==3:
            d.popleft()
            d.append(s4[j])
            j+=1
    if len(d)==3 and d[-1]-d[0]<=l:
        suma+=1
    if len(d)>3 and d[-1]-d[0]<=l:
        x=len(d)-1
        y=x-2
        x=f(x)
        y=2*f(y)
        suma+=int(x/y)
print(suma)


from collections import deque
d=deque()
s1=input()
s2=s1.split()
n=int(s2[0])
l=int(s2[1])
s3=input()
s5=s3.split()
s4=[]
for i in range (n):
    s4.append(int(s5[i]))
suma=0
j=3
i=0
if n>=3 and s4[-1]-s4[0]>l:
    d.append(s4[0])
    d.append(s4[1])
    d.append(s4[2])
    while j!=n:
        if d[-1]-d[0]<=l:
            x=len(d)-1
            x=x*(x-1)
            suma+=int(x/2)
            d.append(s4[j])
            j+=1
        if  d[-1]-d[0]>l and len(d)>3:
            d.popleft()
        elif d[-1]-d[0]>l and len(d)==3:
            d.popleft()
            d.append(s4[j])
            j+=1
    if len(d)>=3 and d[-1]-d[0]<=l:
        x=len(d)-1
        x=x*(x-1)
        suma+=int(x/2)
elif s4[-1]-s4[0]<=l:
    suma+=n*(n-1)
    suma*=n-2
    suma/=6
print(suma)


a,b=input().split()
a=int(a)
b=int(b)
c=input().split()
for i in range(len(c)):
    c[i]=int(c[i])
x=0
t=0
for i in range(a-2):
    while (t<a and c[t]<=c[i]+b):
        t=t+1
    x=x+(t-i-1)*(t-i-2)/2
print(int(x))


def f(n):
    if n>1:
        return n*f(n-1)
    else:
        return 1
from collections import deque
d=deque()
s1=input()
s2=s1.split()
n=int(s2[0])
l=int(s2[1])
s3=input()
s5=s3.split()
s4=[]
for i in range (n):
    s4.append(int(s5[i]))
suma=0
add=0
d.append(s4[0])
d.append(s4[1])
d.append(s4[2])
k=0
k=k+3
while k!=n:
    if len(d)<3 and s4[k]-d[0]<=l:
        d.append(s4[k])
        k+=1
        #print('jin 1')
    elif len(d)<3 and s4[k]-d[0]>l:
        d.append(s4[k])
        k+=1
        d.popleft()
        #print('jin 2')
    elif d[-1]-d[0]<=l and k<n:
        d.append(s4[k])
        k+=1
        #print('jin 3')
        if d[-1]-d[0]>l:
             x=len(d)-2
             y=x-2
             x=f(x)
             y=2*f(y)
             suma+=int(x/y)
             #print('+',suma)
             d.popleft()
             #print('jin 4',k)
    elif d[-1]-d[0]>l:
         d.popleft()
         d.append(s4[k])
         k+=1
         #print('jin5')
if d[-1]-d[0]>l:
    d.pop()
#print('suma ini',suma)
if len(d)>3 and d[-1]-d[0]<=l:
    x=len(d)
    y=x-3
    #print(x)
    x=f(x)
    #print(x)
    y=6*f(y)
    #print('das',y)
    suma+=x/y
    #print('jin 5')
if len(d)==3 and d[-1]-d[0]<=l:
    suma+=1
print(int(suma))


def f(n):
    if n>1:
        return n*f(n-1)
    else:
        return 1
from collections import deque
d=deque()
s1=input()
s2=s1.split()
n=int(s2[0])
l=int(s2[1])
s3=input()
s5=s3.split()
s4=[]
for i in range (n):
    s4.append(int(s5[i]))
suma=0
j=3
i=0
if n>=3:
    d.append(s4[0])
    d.append(s4[1])
    d.append(s4[2])
    while j!=n:
        if d[-1]-d[0]<=l:
            if len(d)==3:
                suma+=1
            elif len(d)>3:
                x=len(d)-1
                y=x-2
                x=f(x)
                y=2*f(y)
                suma+=int(x/y)
            d.append(s4[j])
            j+=1
        if  d[-1]-d[0]>l and len(d)>3:
        d.popleft()
        elif d[-1]-d[0]>l and len(d)==3:
            d.popleft()
            d.append(s4[j])
            j+=1
    if len(d)==3 and d[-1]-d[0]<=l:
    suma+=1
    if len(d)>3 and d[-1]-d[0]<=l:
        x=len(d)-1
        y=x-2
        x=f(x)
        y=2*f(y)
        suma+=int(x/y)
print(suma)


from collections import deque
d=deque()
n,l=input().split()
n=int(n)
l=int(l)
s4=input().split()
for i in range(len(s4)):
    s4[i]=int(s4[i])
s4.append(0)
suma=0
j=0
i=0
x=0
for i in range(n-2):
    while (j<n and s4[j]-s4[i]<=l):
        d.append(s4[j])
        j+=1
    x+=(len(d)-1)*(len(d)-2)/2
    d.popleft()
print(int(x))


from collections import deque
d=deque()
n,l=input().split()
n=int(n)
l=int(l)
s4=input().split()
for i in range(len(s4)):
    s4[i]=int(s4[i])
suma=0
j=3
i=0
if n>=3 and s4[-1]-s4[0]>l:
    d.append(s4[0])
    d.append(s4[1])
    d.append(s4[2])
    for i in range(n-2):
        if d[-1]-d[0]<=l and j<n:
            x=len(d)-1
            x=x*(x-1)
            suma+=int(x/2)
            d.append(s4[j])
            j+=1
        elif d[-1]-d[0]<=l and j>=n:
            x=len(d)-1
            x=x*(x-1)
            suma+=int(x/2)
            d.popleft()
        if  d[-1]-d[0]>l and len(d)>3:
            d.popleft()
        elif d[-1]-d[0]>l and len(d)==3:
            d.popleft()
            if j<n:
                d.append(s4[j])
            j+=1
elif s4[-1]-s4[0]<=l:
    suma+=n*(n-1)
    suma*=n-2
    suma/=6
    suma=int(suma)
print(suma)


def f(n):
    if n>1:
        return n*f(n-1)
    else:
        return 1
from collections import deque
d=deque()
s1=input()
s2=s1.split()
n=int(s2[0])
l=int(s2[1])
s3=input()
s5=s3.split()
s4=[]
for i in range (n):
    s4.append(int(s5[i]))
suma=0
j=3
i=0
d.append(s4[0])
d.append(s4[1])
d.append(s4[2])
while j!=n:
    if d[-1]-d[0]<=l:
        if len(d)==3:
            suma+=1
        elif len(d)>3:
            x=len(d)-1
            y=x-2
            x=f(x)
            y=2*y
            suma+=int(x/y)
        d.append(s4[j])
        j+=1
    if  d[-1]-d[0]>l and len(d)>3:
        d.popleft()
    elif d[-1]-d[0]>l and len(d)==3:
        d.popleft()
        d.append(s4[j])
        j+=1
if len(d)==3 and d[-1]-d[0]<=l:
    suma+=1
if len(d)>3 and d[-1]-d[0]<=l:
    x=len(d)-1
    y=x-2
    x=f(x)
    y=2*f(y)
    suma+=int(x/y)
print(suma)


def f(n):
    if n>1:
        return n*f(n-1)
    else:
        return 1
from collections import deque
d=deque()
s1=input()
s2=s1.split()
n=int(s2[0])
l=int(s2[1])
s3=input()
s5=s3.split()
s4=[]
for i in range (n):
    s4.append(int(s5[i]))
suma=0
j=3
i=0
d.append(s4[0])
d.append(s4[1])
d.append(s4[2])
while j!=n:
    if d[-1]-d[0]<=l:
        if len(d)==3:
            suma+=1
        elif len(d)>3:
            x=len(d)-1
            y=x-2
            x=f(x)
            y=2*f(y)
            suma+=int(x/y)
        d.append(s4[j])
        j+=1
    if  d[-1]-d[0]>l and len(d)>3:
        d.popleft()
    elif d[-1]-d[0]>l and len(d)==3:
        d.popleft()
        d.append(s4[j])
        j+=1
if len(d)==3 and d[-1]-d[0]<=l:
    suma+=1
if len(d)>3 and d[-1]-d[0]<=l:
    x=len(d)-1
    y=x-2
    x=f(x)
    y=2*f(y)
    suma+=int(x/y)
print(suma)


def f(n):
    if n>1:
        return n*f(n-1)
    else:
        return 1
from collections import deque
d=deque()
s1=input()
s2=s1.split()
n=int(s2[0])
l=int(s2[1])
s3=input()
s5=s3.split()
s4=[]
for i in range (n):
    s4.append(int(s5[i]))
suma=0
j=3
i=0
d.append(s4[0])
d.append(s4[1])
d.append(s4[2])
while j!=n:
    if d[-1]-d[0]<=l:
        if len(d)==3:
            suma+=1
        elif len(d)>3:
            x=len(d)-1
            y=x-2
            x=f(x)
            y=2*y
            suma+=int(x/y)
        d.append(s4[j])
        j+=1
    if  d[-1]-d[0]>l and len(d)>3:
        d.popleft()
    elif d[-1]-d[0]>l and len(d)==3:
        d.popleft()
        d.append(s4[j])
        j+=1
if len(d)==3 and d[-1]-d[0]<=l:
    suma+=1
if len(d)>3 and d[-1]-d[0]<=l:
    x=len(d)-1
    y=x-2
    x=f(x)
    y=2*y
    suma+=int(x/y)
print(suma)


from collections import deque
d=deque()
s1=input()
s2=s1.split()
n=int(s2[0])
l=int(s2[1])
s3=input()
s5=s3.split()
s4=[]
for i in range (n):
    s4.append(int(s5[i]))
suma=0
j=3
i=0
if n>=3:
    d.append(s4[0])
    d.append(s4[1])
    d.append(s4[2])
    while j!=n:
        if d[-1]-d[0]<=l:
            x=len(d)-1
            x=x*(x-1)
            suma+=int(x/2)
            d.append(s4[j])
            j+=1
        if  d[-1]-d[0]>l and len(d)>3:
            d.popleft()
        elif d[-1]-d[0]>l and len(d)==3:
            d.popleft()
            d.append(s4[j])
            j+=1
    if len(d)>=3 and d[-1]-d[0]<=l:
        x=len(d)-1
        x=x*(x-1)
        suma+=int(x/2)
print(suma)


from collections import deque
d=deque()
n,l=input().split()
n=int(n)
l=int(l)
s4=input().split()
for i in range(len(s4)):
    s4[i]=int(s4[i])
suma=0
j=3
i=0
if n>=3 and s4[-1]-s4[0]>l:
    d.append(s4[0])
    d.append(s4[1])
    d.append(s4[2])
    while j!=len(s4):
        if d[-1]-d[0]<=l:
            x=len(d)-1
            x=x*(x-1)
            suma+=int(x/2)
            d.append(s4[j])
            j+=1
        if  d[-1]-d[0]>l and len(d)>3:
            d.popleft()
        elif d[-1]-d[0]>l and len(d)==3:
            d.popleft()
            d.append(s4[j])
            j+=1
    if len(d)>=3 and d[-1]-d[0]<=l:
        x=len(d)-1
        x=x*(x-1)
        suma+=int(x/2)
elif s4[-1]-s4[0]<=l:
    suma+=n*(n-1)
    suma*=n-2
    suma/=6
    suma=int(suma)
print(suma)


from collections import deque
d=deque()
n,l=input().split()
n=int(n)
l=int(l)
s4=input().split()
for i in range(len(s4)):
    s4[i]=int(s4[i])
suma=0
j=3
i=0
if n>=3 and s4[-1]-s4[0]>l:
    d.append(s4[0])
    d.append(s4[1])
    d.append(s4[2])
    for i in range(n-2):
        if d[-1]-d[0]<=l and j<n:
            x=len(d)-1
            x=x*(x-1)
            suma+=int(x/2)
            d.append(s4[j])
            j+=1
        elif d[-1]-d[0]<=l and j>=n:
            x=len(d)-1
            x=x*(x-1)
            suma+=int(x/2)
        if  d[-1]-d[0]>l and len(d)>3:
            d.popleft()
        elif d[-1]-d[0]>l and len(d)==3:
            d.popleft()
            d.append(s4[j])
            j+=1
elif s4[-1]-s4[0]<=l:
    suma+=n*(n-1)
    suma*=n-2
    suma/=6
    suma=int(suma)
print(suma)


from collections import deque
d=deque()
n,l=input().split()
n=int(n)
l=int(l)
s4=input().split()
for i in range(len(s4)):
    s4[i]=int(s4[i])
suma=0
j=0
i=0
x=0
d.append(s4[0])
for i in range(n-2):
    while j<n and d[j]<=d[i]+l:
        j+=1
        if j<n:
            d.append(s4[j])
    x+=(len(d)-1)*(len(d)-2)/2
    d.popleft()
print(int(x))


from collections import deque
d=deque()
s1=input()
s2=s1.split()
n=int(s2[0])
l=int(s2[1])
s3=input()
s5=s3.split()
s4=[]
for i in range (n):
    s4.append(int(s5[i]))
suma=0
j=3
i=0
if n>=3 and s4[-1]-s4[0]>l:
    d.append(s4[0])
    d.append(s4[1])
    d.append(s4[2])
    while j!=n:
        if d[-1]-d[0]<=l:
            x=len(d)-1
            x=x*(x-1)
            suma+=int(x/2)
            d.append(s4[j])
            j+=1
        if  d[-1]-d[0]>l and len(d)>3:
            d.popleft()
        elif d[-1]-d[0]>l and len(d)==3:
            d.popleft()
            d.append(s4[j])
            j+=1
    if len(d)>=3 and d[-1]-d[0]<=l:
        x=len(d)-1
        x=x*(x-1)
        suma+=int(x/2)
elif s4[-1]-s4[0]<=l:
    suma+=n*(n-1)
    suma*=n-2
    suma/=6
    suma=int(suma)
print(suma)


n, d = map(int, input().split())
points = [i for i in map(int, input().split())]
i = 0
j = 2
count = 0

while j < n and i < (j - 1):
    diff = points[j] - points[i]
    if diff < d:
        count += (j - i - 1)
        #Fix i, j, there are j - i - 1 numbers between ith and jth numbers that can
        #form a group of 3 distinct numbers with ith and jth numbers
        j += 1
    elif diff == d:
        count += (j - i - 1)
        #print(points[j], points[i+1], i, j-1)
        if (points[j] - points[i + 1] < d) and (i + 1 < j - 1) :
            i += 1
        else:
            i += 1
            j += 1
    else:
        if (points[j] - points[i + 1] < d) and (i + 1 < j - 1) :
            i += 1
        else:
            i += 1
            j += 1

print(count)


n, d = map(int, input().split())
points = [i for i in map(int, input().split())]
i = 0
j = 1
#var count of distinct numbers in a chosen segment in which the distance between two farthest numbers does not exceed d
count = 0
#var result contains the distnct numbers of all possible segments
result = []
#var count_total of the total combination of 3 distinct numbers the distance between the two farthest does not exceed d
count_total = 0

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

#The idea is to fix one i, then j moves to the right until 1) the right number - the left number = d,
#and 2) the number of distinct number between i+1 and j is at least 2 (because i is already a distinct number

while j < n and i < n:
    diff = points[j] - points[i]
    #print("i, j, diff", i, j, diff)
    if diff < d:
        if points[j] != points[j - 1]:
            count += 1
        j += 1
    elif diff == d:
        #print("i, j", i, j)
        if points[j] != points[j - 1]:
            count += 1
        if count >= 2:
            result.append(count + 1) #Need to count the distinct left number, which is number ith
        if points[i+1] != points[i]:
            count -= 1
        j += 1
        i += 1
    else:
        if points[i + 1] != points[i]:
            count -= 1
        i += 1

#print(result)
for num in result:
    total = factorial(num) / factorial(3) / factorial(num - 3)
    #print(int(total))
    count_total += total
print(int(count_total))


n, d = map(int, input().split())
points = [i for i in map(int, input().split())]
i = 0
j = 1
#var count of distinct numbers in a chosen segment in which the distance between two farthest numbers does not exceed d
count = 0
#var result contains the distnct numbers of all possible segments
result = []
#var count_total of the total combination of 3 distinct numbers the distance between the two farthest does not exceed d
count_total = 0

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

#The idea is to fix one i, then j moves to the right until 1) the right number - the left number = d,
#and 2) the number of distinct number between i+1 and j is at least 2 (because i is already a distinct number

while j < n and i < n:
    diff = points[j] - points[i]
    #print("i, j, diff", i, j, diff)
    if diff < d:
        if points[j] != points[j - 1]:
            count += 1
        j += 1
    elif diff == d:
        #print("i, j", i, j)
        if points[j] != points[j - 1]:
            count += 1
        if count >= 2:
            result.append(count + 1) #Need to count the distinct left number, which is number ith
            #after you append count + 1 to result, continue moving i to the right until the new i differs the old i
        j += 1
        i += 1
        if points[i] != points[i-1]:
            count -= 1
        else:
            i += 1
    else:
        i += 1
        if points[i + 1] != points[i]:
            count -= 1
        else:
            i += 1

#print(result)
for num in result:
    total = factorial(num) / factorial(3) / factorial(num - 3)
    #print(int(total))
    count_total += total
print(int(count_total))


n, d = map(int, input().split())
points = [i for i in map(int, input().split())]
i = 0
j = 2
count = 0

#This binary_max returns index of the max number that is smaller or equal than target
def binary_max(list, left, right, target):
    hi = right
    lo = left
    max = list[lo]
    ind = left

    while lo <= hi:
        mid = (hi + lo) // 2
        midval = list[mid]
        if midval > target:
            hi = mid - 1
        elif midval < target:
            if midval > max:
                max = midval
                ind = mid
            lo = mid + 1
        else: #midval == target:
            ind = mid
            break
    return(ind)

#res = binary_max(points, 100)
#print(res)

for i in range(n-2):
    max = points[i] + d
    #Since we start the newe array from i-th, we need to add i to the index returned from the binary search
    #to get the correct index of j-th in the original array points
    end = binary_max(points, i, n-1, max)
    #print("i, max, end", i, max, end)
    #m is the number of distinct numbers between i-th and end, including end
    m = end - i
    #fixing i, we can choose any 2 out of m numbers to form a group of 3 distinct numbers with i-th number
    count += int((m - 1) * m / 2)

print(count)


n, d = map(int, input().split())
points = [i for i in map(int, input().split())]
i = 0
j = 1
#var count of distinct numbers in a chosen segment in which the distance between two farthest numbers does not exceed d
count = 0
#var result contains the distnct numbers of all possible segments
result = []
#var count_total of the total combination of 3 distinct numbers the distance between the two farthest does not exceed d
count_total = 0

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

#The idea is to fix one i, then j moves to the right until 1) the right number - the left number = d,
#and 2) the number of distinct number between i+1 and j is at least 2 (because i is already a distinct number

while j < n and i < n:
    diff = points[j] - points[i]
    #print("i, j, diff", i, j, diff)
    if diff < d:
        if points[j] != points[j - 1]:
            count += 1
        j += 1
    elif diff == d:
        #print("i, j", i, j)
        if points[j] != points[j - 1]:
            count += 1
        if count >= 2:
            result.append(count + 1) #Need to count the distinct left number, which is number ith
            #after you append count + 1 to result, continue moving i to the right until the new i differs the old i
        j += 1
        i += 1
    else:
        i += 1

    if points[i] != points[i-1]:
        count -= 1
    else:
        i += 1

#print(result)
for num in result:
    total = factorial(num) / factorial(3) / factorial(num - 3)
    #print(int(total))
    count_total += total
print(int(count_total))


n, d = map(int, input().split())
points = [i for i in map(int, input().split())]
i = 0
j = 2
count = 0

#This binary search will find the index of the largest number that is smaller or equal to max
#def binary_search(array, target):
#    lower = 0
#    upper = len(array)
#    while lower < upper:   # use < instead of <=
#        x = lower + (upper - lower) // 2
#        val = array[x]
#        if target == val:
#            return x
#        elif target > val:
#            if lower == x:
#                break
#            lower = x
#        elif target < val:
#            upper = x

while j < n and i < (j - 1):
    diff = points[j] - points[i]
    #print("i, j, diff", i, j, diff)
    if diff < d:
        count += (j - i - 1)
        #print("count", count)
        #Fix i, j, there are j - i - 1 numbers between ith and jth numbers that can
        #form a group of 3 distinct numbers with ith and jth numbers
        j += 1
    elif diff == d:
        count += (j - i - 1)
        #print(points[j], points[i+1], i, j-1)
        if (points[j] - points[i + 1] < d) and (i + 1 < j - 1) :
            i += 1
        else:
            #print("T")
            i += 1
            j += 1
    else:
        i += 1

print(count)


n, d = map(int, input().split())
points = [i for i in map(int, input().split())]
i = 0
j = 1
#var count of distinct numbers in a chosen segment in which the distance between two farthest numbers does not exceed d
count = 1
#var result contains the distnct numbers of all possible segments
result = []
#var count_total of the total combination of 3 distinct numbers the distance between the two farthest does not exceed d
count_total = 0

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

while j < n and i < n:
    diff = points[j] - points[i]
    #print("i, j, diff", i, j, diff)
    if diff < d:
        if points[j] != points[j - 1]:
            count += 1
        j += 1
    elif diff == d:
        #print("i, j", i, j)
        if points[j] != points[j - 1]:
            count += 1
        if count >= 3:
            result.append(count)
        if points[i+1] != points[i]:
            count -= 1
        j += 1
        i += 1
    else:
        if points[i + 1] != points[i]:
            count -= 1
        i += 1

#print(result)
for num in result:
    total = factorial(num) / factorial(3) / factorial(num - 3)
    #print(int(total))
    count_total += total
print(int(count_total))


n, d = map(int, input().split())
points = [i for i in map(int, input().split())]
i = 0
j = 1
#var count of distinct numbers in a chosen segment in which the distance between two farthest numbers does not exceed d
count = 0
#var result contains the distnct numbers of all possible segments
result = []
#var count_total of the total combination of 3 distinct numbers the distance between the two farthest does not exceed d
count_total = 0

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

#The idea is to fix one i, then j moves to the right until 1) the right number - the left number = d,
#and 2) the number of distinct number between i+1 and j is at least 2 (because i is already a distinct number

while j < n and i < n:
    diff = points[j] - points[i]
    #print("i, j, diff", i, j, diff)
    if diff < d:
        if points[j] != points[j - 1]:
            count += 1
        j += 1
    elif diff == d:
        #print("i, j", i, j)
        if points[j] != points[j - 1]:
            count += 1
        if count >= 2:
            result.append(count + 1) #Need to count the distinct left number, which is number ith
            #after you append count + 1 to result, continue moving i to the right until the new i differs the old i
        j += 1
        i += 1
        while points[i] == points[i-1] and i < j:
            i += 1
        count -= 1
    else:
        i += 1
        while points[i] == points[i - 1] and i < j:
            i += 1
        count -= 1

#print(result)
for num in result:
    total = factorial(num) / factorial(3) / factorial(num - 3)
    #print(int(total))
    count_total += total
print(int(count_total))


n, d = map(int, input().split())
points = [i for i in map(int, input().split())]
i = 0
j = 1
#var count of distinct numbers in a chosen segment in which the distance between two farthest numbers does not exceed d
count = 0

#def factorial(n):
#    if n == 0:
#        return 1
#    else:
#        return n * factorial(n-1)

#The idea is to fix one i, then j moves to the right until 1) the right number - the left number = d,
#and 2) the number of distinct number between i+1 and j is at least 2 (because i is already a distinct number

for i in range(n):
    j = i + 2
    while (j < n) and (points[j] - points[i] <= d):
        count += (j - i - 1)
        j += 1

print(count)


n, d = map(int, input().split())
points = [i for i in map(int, input().split())]
i = 0
j = 1
#var count of distinct numbers in a chosen segment in which the distance between two farthest numbers does not exceed d
count = 0
#var result contains the distnct numbers of all possible segments
result = []
#var count_total of the total combination of 3 distinct numbers the distance between the two farthest does not exceed d
count_total = 0

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

#The idea is to fix one i, then j moves to the right until 1) the right number - the left number = d,
#and 2) the number of distinct number between i+1 and j is at least 2 (because i is already a distinct number

while j < n and i < n:
    diff = points[j] - points[i]
    #print("i, j, diff", i, j, diff)
    if diff < d:
        if points[j] != points[j - 1]:
            count += 1
        j += 1
    elif diff == d:
        #print("i, j", i, j)
        if points[j] != points[j - 1]:
            count += 1
        if count >= 2:
            result.append(count + 1) #Need to count the distinct left number, which is number ith
            #after you append count + 1 to result, move i to the right until the new i differs the old i
            i += 1
            if points[i] == points[i-1]:
                i += 1
            else:
                count -= 1
        j += 1
    else:
        if points[i + 1] != points[i]:
            count -= 1
        i += 1

#print(result)
for num in result:
    total = factorial(num) / factorial(3) / factorial(num - 3)
    #print(int(total))
    count_total += total
print(int(count_total))


n, d = map(int, input().split())
points = [i for i in map(int, input().split())]
i = 0
j = 2
count = 0

#This binary_max returns index of the max number that is smaller or equal than target
def binary_max(list, target):
    hi = len(list) - 1
    lo = 0
    midpoint = (hi + lo) // 2
    max = list[midpoint]
    ind = midpoint

    while lo <= hi:
        mid = (hi + lo) // 2
        midval = list[mid]
        if midval > target:
            hi = mid - 1
        elif midval < target:
            if midval > max:
                max = midval
                ind = mid
            lo = mid + 1
        else: #midval == target:
            ind = mid
            break
    return(ind)

#res = binary_max(points, 100)
#print(res)

for i in range(n-2):
    max = points[i] + d
    #Since we start the newe array from i-th, we need to add i to the index returned from the binary search
    #to get the correct index of j-th in the original array points
    end = binary_max(points[i:], max) + i
    #print("i, max, end", i, max, end)
    #m is the number of distinct numbers between i-th and end, including end
    m = end - i
    #fixing i, we can choose any 2 out of m numbers to form a group of 3 distinct numbers with i-th number
    count += int((m - 1) * m / 2)

print(count)


n, d = map(int, input().split())
points = [i for i in map(int, input().split())]
i = 0
j = 2
count = 0

#This binary_max returns index of the max number that is smaller or equal than target
def binary_max(list, left, right, target):
    hi = right
    lo = left
    max = list[lo]
    ind = left

    while lo <= hi:
        mid = (hi + lo) // 2
        midval = list[mid]
        if midval > target:
            hi = mid - 1
        elif midval < target:
            if midval > max:
                max = midval
                ind = mid
            lo = mid + 1
        else: #midval == target:
            ind = mid
            break
    return(ind)

#res = binary_max(points, 100)
#print(res)

for i in range(n-2):
    max = points[i] + d
    #Since we start the newe array from i-th, we need to add i to the index returned from the binary search
    #to get the correct index of j-th in the original array points
    end = binary_max(points, i, n-1 max)
    #print("i, max, end", i, max, end)
    #m is the number of distinct numbers between i-th and end, including end
    m = end - i
    #fixing i, we can choose any 2 out of m numbers to form a group of 3 distinct numbers with i-th number
    count += int((m - 1) * m / 2)

print(count)


n,d=map(int,input().split())
a=list(map(int,input().split()))
ans=0
for i in range(n):
    s=i+1
    e=n-1
    while(s<e):
        if a[s]-a[i]<d:
            s=s+1
        if a[e]-a[i]>d:
            e=e-1
    if a[e]-a[i]<=d:
        e=e
    else:
        e=e-1
    if e-i>=2:
        ans=ans+(e-i)*(e-i-1)//2
print(ans)


n,d=map(int,input().split())
a=list(map(int,input().split()))
ans,j=0,0
for i in range(n):
    while a[i]-a[j]>d:
        j+=1
    v=i-j
    ans=ans+v*(v-1)//2
print(ans)


n,d=map(int,input().split())
a=list(map(int,input().split()))
ans=0
for i in range(n):
    s=i
    e=n-1
    while(s<e):
        if a[s]-a[i]<d:
            s=s+1
        if a[e]-a[i]>d:
            e=e-1
  #  print(e)
    if e-i>=2:
        ans=ans+(e-i)*(e-i-1)//2
print(ans)


def check(l , count , n , d):
    i = 0
    j = 2
    while j <= n-1:
        if abs(l[j] - l[i]) <= d:
            count += 1
            j +=1
        else:
            j +=1
    return count

n , d = map(int , input().split(' '))

l = list(map(int ,input().split(' ')))

count = 0

first = check(l,count ,n , d )

second = check(sorted(l , reverse=True),count ,n , d )

print(first + second)


n , d = map(int , input().split(' '))

l = list(map(int ,input().split(' ')))

ans = 0
i = 0
j = 0
while n>i :
    while l[i]-l[j] > d: # when the condition is not working make a step
        j +=1

    ans += ((i-j)*(i-j-1))//2

    i +=1

print(ans)


n,d=input().split(' ')
n=int(n)
d=int(d)
queue=[int(i) for i in input().split()]
ans=0
def find_max(begin,start,end):
    while start < end:
        mid=(start+end)//2
        if queue[mid]-queue[begin]<=d:
            start=mid+1
        else:
            end=mid
    mid=(start+end)//2
    if queue[mid]-queue[begin]>d:
        mid-=1
    return mid
for i in range(n-2):
    if i==0:
        j=find_max(i,i+2,n-1)
    else:
        j=find_max(i,j,n-1)
    if j-i<2:
        continue
    else:
        ans+=(j-i)*(j-i-1)//2
print(ans)


import os;
[n,d]=[int(i) for i in input().split()];
x=[int(i) for i in input().split()];
s=0;
#print(n);
if(n<=2):
    print(0);
    os.exit();
for i in range(0,n-2):
    for j in range(i+2,n):
        if(x[j]-x[i]<=d):
            s=s+j-i-1;
print(s);


[n,d]=[int(i) for i in input().split()];
x=[int(i) for i in input().split()];
s=0;
if(n>2):
    j=2;
    for i in range(0,n-2):
        while((j<n) and (x[j]-x[i]<=d)):
            j=j+1
        s=s+(j-i-1)*(j-i-2)//2;
    print(s);
else:
    print(0);


[n,m]=[int(i) for i in input().split()];
a=[int(i) for i in input().split()];
t=m*[0];
r=m*[0];
lastt=-1;
for i in range(0,m):
    [t[i],r[i]]=[int(i) for i in input().split()];
mm=r.index(max(r));
while(True):
    if(t[mm]!=lastt):
#        print("sorted")
        if(t[mm]==1):
            a[:r[mm]]=sorted(a[:r[mm]]);
        else:
            a[:r[mm]]=sorted(a[:r[mm]],reverse=True);
#    print(a);
    if(mm==m-1):
        break;
    lastt=t[mm];
    mm=r.index(max(r[mm+1:]));
for i in a:
    print(i,end=" ")


import os;
[n,d]=[int(i) for i in input().split()];
x=[int(i) for i in input().split()];
s=0;
#print(n);
if(n>2):
    for i in range(0,n-2):
        for j in range(i+2,n):
            if(x[j]-x[i]<=d):
                s=s+j-i-1;
    print(s);
else:
    print(0);


[n,m]=[int(i) for i in input().split()];
a=[int(i) for i in input().split()];
t=m*[0];
r=m*[0];
lastt=-1;
for i in range(0,m):
    [t[i],r[i]]=[int(i) for i in input().split()];
mm=r.index(max(r));
while(True):
    if(t[mm]!=lastt):
        if(t[mm]==1):
            a[:r[mm]]=sorted(a[:r[mm]]);
        else:
            a[:r[mm]]=sorted(a[:r[mm]],reverse=True);
    if(mm==m-1):
        break;
    lastt=t[mm];
    mm=r.index(max(r[mm+1:]));
for i in a:
    print(i,end=" ")


# -*- coding: utf-8 -*-
"""
Created on Mon May 16 17:14:14 2016

@author: Hangell
"""

str1=input()
str2=input()
n=int(str1.split()[0])
d=int(str1.split()[1])
numlist=str2.split()
for i in range(n):
    numlist[i]=int(numlist[i])
sum=0
for i in range (n-2):
    j=i+2
    while j!=n and numlist[j]<=numlist[i]+d:
        j=j+1
    sum=sum+j-i-2
print(int(sum))


# -*- coding: utf-8 -*-
"""
Created on Mon May 16 17:14:14 2016

@author: Hangell
"""
from collections import deque

str1=input()
str2=input()
n=int(str1.split()[0])
d=int(str1.split()[1])
numlist=str2.split()
newdeque=deque()
Sum=0
cha=0
way=0
for i in range(n):
    numlist[i]=int(numlist[i])

for i in range(n-1):
    cha=numlist[i+1]-numlist[i]
    newdeque.append(cha)
    Sum+=cha
    while Sum>d and len(newdeque)!=0:
        Sum-=newdeque.popleft()

    if len(newdeque)>1:
        way+=(len(newdeque)-1)*len(newdeque)/2
print(int(way))


# -*- coding: utf-8 -*-
"""
Created on Mon May 16 17:14:14 2016

@author: Hangell
"""

str1=input()
str2=input()
n=int(str1.split()[0])
d=int(str1.split()[1])
numlist=str2.split()
for i in range(n):
    numlist[i]=int(numlist[i])
sum=0
for i in range (n-2):
    j=i+2
    while j!=n and numlist[j]<=numlist[i]+d:
        j=j+1
    sum=sum+(j-i-2)*(j-i-1)/2
print(int(sum))


n, d = map(int, input().split())
a = list(map(int, input().split()))
j = 0
cnt = 0
for i in range(n):
	while a[i] - a[j] > d:
		j += 1
	k = i - j
	cnt += k * (k - 1) // 2
print(cnt)


def fact(x, y):
    ans = 1
    for i in range(x-y+1, x+1):
        ans *= i
    return ans

n, k = map(int, input().split())
a = list(map(int, input().split())); a.append(10**12 + 1)
i, j, t = 0, 2, []
while j < n+1:
    if a[j] - a[i] > k:
        if j - i >= 3 and a[j-1] - a[i] <= k:
            t.append( (i, j) )
        i += 1
    if a[j] - a[i] <= k or j - i < 2:
        j += 1

ans = 0
for a, b in t:
    ans += fact(b-a, 3) // fact(3, 3)
for i in range(1, len(t)):
    start, end = t[i][0], t[i-1][1]
    if end - start >= 3:
        ans -= fact(end-start, 3) // fact(3, 3)
print(ans)


def fact(x, y):
    ans = 1
    for i in range(x-y+1, x+1):
        ans *= i
    return ans

n, k = map(int, input().split())
a = list(map(int, input().split())); a.append(10**12 + 1)
i, j, t = 0, 2, []
while j < n+1:
    if a[j] - a[i] > k:
        if j - i >= 3 and a[j-1] - a[i] <= k:
            t.append( (i, j) )
        i += 1
    j += 1

ans = 0
for a, b in t:
    ans += fact(b-a, 3) // fact(3, 3)
for i in range(1, len(t)):
    start, end = t[i][0], t[i-1][1]
    if end - start >= 3:
        ans -= fact(end-start, 3) // fact(3, 3)
print(ans)


n,d=[int(i) for i in input().split()]
jj=[int(i) for i in input().split()]
ll=0
for i in range(n-2):
    for k in range(n-1,i+1,-1):
        if jj[k]-jj[i]<=d:
            s=k-i
            ll+=s*(s-1)/2
            break
print(int(ll))


n,d=[int(i) for i in input().split()]
jj=[int(i) for i in input().split()]
ll=0
s=0
for i in range(n-1,1,-1):
    if jj[i]-jj[s]<=d:
        break
ll+=(i**2-1)*i/6
for j in range(i+1,n):
    while jj[j]-jj[s]>d:
        s+=1
    ll+=(j-s)*(j-s-1)/2
print(int(ll))


n,d=[int(i) for i in input().split()]
jj=[int(i) for i in input().split()]
ll=0
for i in range(n-2):
    jjj=jj[i]
    for k in range(i+2,n):
        if jj[k]-jjj<=d:
            ll+=k-i-1
        else:
            break
print(ll)


n,d=[int(i) for i in input().split()]
jj=[int(i) for i in input().split()]
ll=0
for i in range(n-2):
    for k in range(i+2,n):
        if jj[k]-jj[i]<=d:
            ll+=k-i-1
        else:
            break
print(ll)


n,d=[int(i) for i in input().split()]
jj=[int(i) for i in input().split()]
ll=0
s=0
if n<=2:
    print(0)
    exit()
for i in range(n-1,1,-1):
    if jj[i]-jj[s]<=d:
        ll+=(i**2-1)*i/6
        break
for j in range(i+1,n):
    while jj[j]-jj[s]>d:
        s+=1
    ll+=(j-s)*(j-s-1)/2
print(int(ll))


n,d=[int(i) for i in input().split()]
jj=[int(i) for i in input().split()]
ll=0
s=0
for i in range(n-1,1,-1):
    if jj[i]-jj[s]<=d:
        ll+=(i**2-1)*i/6
        break
for j in range(i+1,n):
    while jj[j]-jj[s]>d:
        s+=1
    ll+=(j-s)*(j-s-1)/2
print(int(ll))


n, m = map(int, input().split())
ar = sorted(map(int, input().split()))
res, b, e = 0, 0, 0
while e < n-1:
    e += 1
    while ar[e] - ar[b] > m:
        b += 1
    res += ((e-b) * (e-b-1)) >> 1
print(res)


def cnk(n):
    return 0 if 3 > n else n * (n - 1) * (n - 2) // 6

n, d = input().split()
n, d = int(n), float(d)
dots = list(map(int, input().split()))

l, r, res = 0, 0, 0
while l < n:
    while r < n and dots[r] - dots[l] <= d:
        r += 1

    res += cnk(r - l)
    if r == n:
        break

    while l < r and dots[r] - dots[l] > d:
        l += 1

print(res)


def cnk(n):
    return 0 if 2 > n else n * (n - 1) // 2

n, d = input().split()
n, d = int(n), float(d)
dots = list(map(int, input().split()))

l, r, res = 0, 0, 0
while r < n:
    while l < r and dots[r] - dots[l] > d:
        l += 1
    res += cnk(r - l)
    r += 1

print(res)


n, d = map(int, input().split())
d += 1
t = list(map(int, input().split())) + [1000000001 + d]
s, j = 0, 2
for i in range(n - 2):
    while t[j] - t[i] < d: j += 1
    k = j - i - 1
    if k > 1: s += k *(k - 1)
print(s // 2)


from bisect import bisect_right

num_points, max_distance = map(int, input().split())
points = list(map(int, input().split()))
solution = 0
for pos_point_min, point_min in enumerate(points):
    point_max = point_min + max_distance
    pos_point_max = bisect_right(points, point_max) - 1
    num_middle_points = pos_point_max - pos_point_min
    if num_middle_points > 0:
        solution += num_middle_points * (num_middle_points-1) // 2
print(solution)


from bisect import bisect_right
from functools import reduce
from operator import mul    # or mul=lambda x,y:x*y
from fractions import Fraction

def ncr(n, r):
    return int(reduce(mul, (Fraction(n-i, i+1) for i in range(r)), 1))

num_points, max_distance = map(int, input().split())
points = list(map(int, input().split()))
solution = 0
for pos_point_min, point_min in enumerate(points):
    point_max = point_min + max_distance
    pos_point_max = bisect_right(points, point_max) - 1
    num_middle_points = pos_point_max - pos_point_min
    if num_middle_points > 0:
        solution += ncr(num_middle_points, 2)
print(solution)


if __name__ == "__main__":
    n, d = map(int, input().split())
    a = list(map(int, input().split()))
    num_ways = 0
    j = 0
    for i in range(n):
        while j < n and a[j] - a[i] <= d:
            j += 1
        num = j - i # we have num elements from i to j-1
        num_ways += (num - 1) * (num - 2) // 2
    print(num_ways)


n,d=[int(i) for i in input().split()]

x=[int(i) for i in input().split()]

k=0

S=0

for i in range(2,n):

    while x[i]-x[k]>d:k=k+1

    P=i-k

    S+=P*(P-1)//2

print(S)


import math

n, d = map(int, input().split())
x = [int(i) for i in input().split()]

num_of_options = 0
ind = 0
ind2 = 0
subtract = 0
flag = 1
while ind2 < n:
    # print(num_of_options)
    if abs(x[ind2] - x[ind]) <= d:
        ind2 += 1
        flag = 1
    else:
        if ind2 - ind - 3 >= 0 and subtract - ind - 3 >= 0:
            num_of_options += math.factorial(ind2 - ind) // (math.factorial(3) * math.factorial(ind2 - ind - 3)) - \
                              math.factorial(subtract - ind) // (math.factorial(3) * math.factorial(subtract - ind - 3))
        elif ind2 - ind - 3 >= 0:
            num_of_options += math.factorial(ind2 - ind) // (math.factorial(3) * math.factorial(ind2 - ind - 3))
        flag = 0
        subtract = ind2
        while abs(x[ind2] - x[ind]) > d:
            ind += 1

if flag == 1:
    if ind2 - ind - 3 >= 0 and subtract - ind - 3 >= 0:
        num_of_options += math.factorial(ind2 - ind) // (math.factorial(3) * math.factorial(ind2 - ind - 3)) - \
                          math.factorial(subtract - ind) // (math.factorial(3) * math.factorial(subtract - ind - 3))
    elif ind2 - ind - 3 >= 0:
        num_of_options += math.factorial(ind2 - ind) // (math.factorial(3) * math.factorial(ind2 - ind - 3))

print(num_of_options)


import math

n, d = map(int, input().split())
x = [int(i) for i in input().split()]

num_of_options = 0
ind = 0
ind2 = 0
subtract = 0
flag = 1
while ind2 < n:
    if abs(x[ind2] - x[ind]) <= d:
        ind2 += 1
        flag = 1
    else:
        if ind2 - ind - 3 >= 0 and subtract - ind - 3 >= 0:
            num_of_options += math.factorial(ind2 - ind) // (math.factorial(3) * math.factorial(ind2 - ind - 3)) - \
                              math.factorial(subtract - ind) // (math.factorial(3) * math.factorial(subtract - ind - 3))
        elif ind2 - ind - 3 >= 0:
            num_of_options += math.factorial(ind2 - ind) // (math.factorial(3) * math.factorial(ind2 - ind - 3))
        flag = 0
        subtract = ind2 - 1
        while abs(x[ind2] - x[ind]) > d:
            ind += 1

if flag == 1:
    if ind2 - ind - 3 >= 0 and subtract - ind - 3 >= 0:
        num_of_options += math.factorial(ind2 - ind) // (math.factorial(3) * math.factorial(ind2 - ind - 3)) - \
                          math.factorial(subtract - ind) // (math.factorial(3) * math.factorial(subtract - ind - 3))
    elif ind2 - ind - 3 >= 0:
        num_of_options += math.factorial(ind2 - ind) // (math.factorial(3) * math.factorial(ind2 - ind - 3))

print(num_of_options)


n, d = map(int, input().split())
x = [int(i) for i in input().split()]

amounts = [1]
for num in range(2, 10**5):
    amounts.append(amounts[-1] + num)

# print(amounts[:100])

num_of_options = 0
ind = 0
ind2 = 0
while ind2 < n:
    # print(num_of_options)
    if abs(x[ind] - x[ind2]) <= d:
        if ind2 - ind >= 2:
            num_of_options += amounts[ind2 - ind - 2]
        ind2 += 1
    else:
        while abs(x[ind] - x[ind2]) > d:
            ind += 1

print(num_of_options)


from collections import deque
n,m = [int(i) for i in input().split()]
list_inp = input().split()
D = deque()
ways=0

for i in range(n-1):
    t=sum(D)
    while t+int(list_inp[i+1])-int(list_inp[i])>m and len(D)>0:
        D.popleft()
    if t+int(list_inp[i+1])-int(list_inp[i]) <= m:
        ways += int(len(D)*(len(D)+1)/2)
        D.append(int(list_inp[i+1])-int(list_inp[i]))
print (ways)


a,b=input().split()
a=int(a)
b=int(b)
c=input().split()
for i in range(len(c)):
    c[i]=int(c[i])
x=0
t=0
for i in range(a-2):
    while (t<a and c[t]<=c[i]+b):
        t=t+1
    x=x+t-i-1+(t-i-1)*(t-i-2)/2
print(int(x))


from collections import deque
n,m = [int(i) for i in input().split()]
list_inp = input().split()
D = deque()
ways=0

for i in range(n-1):
    while sum(D)+int(list_inp[i+1])-int(list_inp[i])>m and len(D)>0:
        D.popleft()
    if sum(D)+int(list_inp[i+1])-int(list_inp[i]) <= m:
        ways += int(len(D)*(len(D)+1)/2)
        D.append(int(list_inp[i+1])-int(list_inp[i]))
print (ways)


a,b=input().split()
a=int(a)
b=int(b)
c=input().split()
for i in range(len(c)):
    c[i]=int(c[i])
x=0
def function(c):
    global x
    for p in range(len(c)-2):
        if c[0]+b>=c[2+p]:
            x=x+p+1
while len(c)>=3:
    function(c)
    c.pop(0)

print(int(x))


from collections import deque
n,m = [int(i) for i in input().split()]
list_inp = input().split()
D = deque()
ways=0

for i in range(n-1):
    while sum(D)+int(list_inp[i+1])-int(list_inp[i])>m and len(D)>0:
        D.popleft()
    if sum(D)+int(list_inp[i+1])-int(list_inp[i]) <= m:
        ways += int(len(D)*(len(D)+1)/2)
        D.append(int(list_inp[i+1])-int(list_inp[i]))
        print(D)
print (ways)


from collections import deque
n,m = [int(i) for i in input().split()]
list_inp = input().split()
D = deque()
ways=0

for i in range(n-1):
    t=sum(D)
    while t+int(list_inp[i+1])-int(list_inp[i])>m and len(D)>0:
        D.popleft()
        t=sum(D)
    if t+int(list_inp[i+1])-int(list_inp[i]) <= m:
        ways += int(len(D)*(len(D)+1)/2)
        D.append(int(list_inp[i+1])-int(list_inp[i]))

print (ways)


a,b=input().split()
a=int(a)
b=int(b)
c=input().split()
for i in range(len(c)):
    c[i]=int(c[i])
x=0
for i in range(a-2):
    for p in range(a-i-2):
        if c[0+i]+b>=c[2+i+p]:
            x+=p+1
print(int(x))


a,b=input().split()
a=int(a)
b=int(b)
c=input().split()
for i in range(len(c)):
    c[i]=int(c[i])
x=0
t=0
for i in range(a-2):
    while (c[t]<=c[i]+b and t<a):
        t=t+1
    t-i-1
    x=x+(t-i-1)*(t-i-2)/2
print(int(x))


from collections import deque
n,m = [int(i) for i in input().split()]
list_inp = input().split()
D = deque()
ways=0

for i in range(n-1):
    t=sum(D)
    while t+int(list_inp[i+1])-int(list_inp[i])>m and len(D)>0:
        D.popleft()
        t=sum(D)
    if t+int(list_inp[i+1])-int(list_inp[i]) <= m:
        ways += int(len(D)*(len(D)+1)/2)
        D.append(int(list_inp[i+1])-int(list_inp[i]))
print (ways)


a,b=input().split()
a=int(a)
b=int(b)
c=input().split()
for i in range(len(c)):
    c[i]=int(c[i])
x=0
t=0
for i in range(a-2):
    while (c[t]<=c[i]+b and t<a):
        t=t+1
    x=x+t-i-1+(t-i-1)*(t-i-2)/2
print(int(x))


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

const int MAXN = 1e5 + 100;

int N, K, W;
bool candy[MAXN];

int pref[MAXN];
int sum[MAXN][10];
int qua[MAXN][10];

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0), cout.tie(0), cout.precision(15);

    cin >> N >> K >> W;

    for (int i = 1; i <= N; i++) {
        char c;
        cin >> c;
        candy[i] = (c == '1');

        pref[i] = pref[i-1] + int(candy[i]);

        for (int r = 0; r < K; r++) {
            sum[i][r] = sum[i-1][r];
            qua[i][r] = qua[i-1][r];
        }

        sum[i][i%K]+= int(candy[i]);
        qua[i][i%K]++;
    }

    for (int i = 0; i < W; i++) {
        int L, R;
        cin >> L >> R;

        int res = (L + K - 1) % K;

        int boxes = qua[R][res] - qua[L-1][res];
        int good = sum[R][res] - sum[L-1][res];
        int total = pref[R] - pref[L-1];

        cout << (total - good) + (boxes - good) << "\n";
    }
}


#include <iostream>
#include<bits/stdc++.h>
using namespace std;

int sum[100001],dp[100001][20];

int main()
{
    int i,j,n,k,q,ans=0,l,r;
    string str;
    cin>>n>>k>>q;
    cin>>str;
    sum[0]=0;
    for(i=0;i<n;i++)
    {
        if(str[i]=='1')
        sum[i+1]=sum[i]+1;
        else
        sum[i+1]=sum[i];
    }
    for(i=1;i<=k;i++)
    {
        for(j=i+k-1;j<=n;j+=k)
        {
            if(str[j-1]=='1')
            dp[j][i]=dp[j-k][i]-1;
            else
            dp[j][i]=dp[j-k][i]+1;

        }
    }
    while(q--)
    {
        cin>>l>>r;
        ans=sum[r]-sum[l-1];
        i=l%k;
        if(!i)
        i=k;
        ans+=dp[r][i]-dp[l-1][i];
        cout<<ans<<endl;

    }
    // your code goes here
    return 0;
}


#include <iostream>
#include<bits/stdc++.h>
using namespace std;

int sum[100001],dp[1001][20];

int main()
{
    int i,j,n,k,q,ans=0,l,r;
    string str;
    cin>>n>>k>>q;
    cin>>str;
    sum[0]=0;
    for(i=0;i<n;i++)
    {
        if(str[i]=='1')
        sum[i+1]=sum[i]+1;
        else
        sum[i+1]=sum[i];
    }
    for(i=1;i<=k;i++)
    {
        for(j=i+k-1;j<=n;j+=k)
        {
            if(str[j-1]=='1')
            dp[j][i]=dp[j-k][i]-1;
            else
            dp[j][i]=dp[j-k][i]+1;

        }
    }
    while(q--)
    {
        cin>>l>>r;
        ans=sum[r]-sum[l-1];
        i=l%k;
        if(!i)
        i=k;
        ans+=dp[r][i]-dp[l-1][i];
        cout<<ans<<endl;

    }
    // your code goes here
    return 0;
}


//there’s light at end of every dark tunnel...keep moving
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define inf 1000000000000
#define mod 1000000007
#define pb push_back
#define mp make_pair
#define all(v) v.begin(),v.end()
#define S second
#define F first
#define boost ios::sync_with_stdio(false);

ll a[1000001],sum[1000001],dp[1000001];
int main()
{
	ll i,j,n,k,q,tot,to_add,to_sub,l,r,x;
	string s;
	cin>>n>>k>>q;
	cin>>s;
	s=" "+s;
	for(i=1;i<=n;i++)
	{
		a[i]=s[i]-'0';
		sum[i]=sum[i-1]+a[i];
	}
	for(i=1;i<=n;i++)
	dp[i]=dp[max(0LL,i-k)]+a[i];
	while(q--)
	{
		cin>>l>>r;
		x=dp[r]-dp[l-1];
		to_add=(r-l+1)/k-x;
		tot=sum[r]-sum[l-1];
		to_sub=tot-x;
		cout<<to_add+to_sub<<endl;
	}
	return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define f(w,e,y) for(ll w=e;w<y;w++)
#define ff(w,e,y) for(ll w=e;w<=y;w++)
#define mem(x,y) memset(x,y,sizeof(x))

using namespace std;

ll a[100004],s[100004];

int main()
{
    ll n,m,k;

    cin>>n>>m>>k;

    string st;

    cin>>st;

    a[0]=0;
    s[0]=0;

    ff(i,1,n)
    {
        ll g=st[i-1]-'0';
        a[i]=a[i-1];
        if(i%k==0)
        {
            if(g==1)
                a[i]++;

        }
        s[i]=s[i-1]+g;
    }

    ll l,r;
//
//    for(ll i=1;i<=n;i++)
//        cout<<a[i]<<" ";cout<<endl;
//    for(ll i=1;i<=n;i++)
//        cout<<s[i]<<" ";cout<<endl;

    ff(i,1,m)
    {
        cin>>l>>r;

        if(l!=r)
        {
            ll ans=0;

            ll f=r/k;

            ll d=(l-1)/k;

            ll t=f-d;

//            cout<<"t="<<t<<endl;

            ll q=a[r]-a[l-1];

            if(q<t)
            {
                ans+=(t-q);
            }
//            else if(t>q)
//                ans+=(q-t);

            ll qq=s[r]-s[l-1];

            ll ss=qq-q;

            if(ss>0)
                ans+=ss;
            cout<<ans<<endl;
        }
        else
        {
            if(k==1)
            {
                if(st[r-1]=='1')
                    cout<<"0"<<endl;
                else
                    cout<<"1"<<endl;
            }
            else
                cout<<"0"<<endl;
        }
    }
//    main();
    return 0;

}


#include<bits/stdc++.h>
#define ll long long
#define f(w,e,y) for(ll w=e;w<y;w++)
#define ff(w,e,y) for(ll w=e;w<=y;w++)
#define mem(x,y) memset(x,y,sizeof(x))

using namespace std;

ll a[100004],s[100004];

int main()
{
    ll n,m,k;

    cin>>n>>m>>k;

    string st;

    cin>>st;

    a[0]=0;
    s[0]=0;

    ff(i,1,n)
    {
        ll g=st[i-1]-'0';
        if(i%k==0)
        {
            if(g==1)
                a[i]=a[i-1]+1;
        }
        s[i]=s[i-1]+g;
    }

    ll l,r;

    ff(i,1,m)
    {
        cin>>l>>r;

        if(l!=r)
        {
            ll ans=0;

            ll f=r/k;

            ll d=(l-1)/k;

            ll t=f-d;

            ll q=a[r]-a[l-1];

            if(q<t)
            {
                ans+=(t-q);
            }

            q=s[r]-s[l-1];

            if(q>t)
            {
                ans+=(q-t);
            }
            cout<<ans<<endl;
        }
        else
        {
//            if(k==1)
//            {
//                if(st[r-1]=='1')
//                    cout<<"0"<<endl;
//                else
                    cout<<"0"<<endl;
//            }
        }

    }
//    main();
    return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define f(w,e,y) for(ll w=e;w<y;w++)
#define ff(w,e,y) for(ll w=e;w<=y;w++)
#define mem(x,y) memset(x,y,sizeof(x))

using namespace std;

ll a[100004],s[100004];

int main()
{
    ll n,m,k;

    cin>>n>>k>>m;

    string st;

    cin>>st;

    a[0]=0;
    s[0]=0;

    ff(i,1,n)
    {
        ll g=st[i-1]-'0';

        if(g==1)
        {
            if(i%k==0)
                a[i]=a[i-1]+1;
            else
                a[i]=a[i-1];
        }
        else
            a[i]=a[i-k];
        s[i]=s[i-1]+g;
    }

    ll l,r;
    ff(i,1,m)
    {
        cin>>l>>r;

        if(l!=r)
        {
            ll ans=0;

            ll f=r/k;

            ll d=(l-1)/k;

            ll t=(f-d);

            ll q=a[r]-a[l-1];

            if(q<t)
            {
                ans+=(t-q);
            }
//            else if(t>q)
//                ans+=(q-t);

            ll qq=s[r]-s[l-1];

            ll ss=qq-q;

            if(ss>0)
                ans+=ss;
            cout<<ans<<endl;
        }
        else
        {
            if(k==1)
            {
                if(st[r-1]=='1')
                    cout<<"0"<<endl;
                else
                    cout<<"1"<<endl;
            }
            else
                cout<<"0"<<endl;
        }
    }
    return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define f(w,e,y) for(ll w=e;w<y;w++)
#define ff(w,e,y) for(ll w=e;w<=y;w++)
#define mem(x,y) memset(x,y,sizeof(x))

using namespace std;

ll a[100004],s[100004];

int main()
{
    ll n,m,k;

    cin>>n>>m>>k;

    string st;

    cin>>st;

    a[0]=0;
    s[0]=0;

    ff(i,1,n)
    {
        ll g=st[i-1]-'0';
        if(i%k==0)
        {
            if(g==1)
                a[i]=a[i-1]+1;
        }
        s[i]=s[i-1]+g;
    }

    ll l,r;

    ff(i,1,m)
    {
        cin>>l>>r;

        if(l!=r)
        {
            ll ans=0;

            ll f=r/k;

            ll d=(l-1)/k;

            ll t=f-d;

            ll q=a[r]-a[l-1];

            if(q<t)
            {
                ans+=(t-q);
            }

            q=s[r]-s[l-1];

            if(q>t)
            {
                ans+=(q-t);
            }
            cout<<ans<<endl;
        }
        else
        {
            if(k==1)
            {
                if(st[r-1]=='1')
                    cout<<"0"<<endl;
                else
                    cout<<"1"<<endl;
            }
        }

    }
//    main();
    return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define f(w,e,y) for(ll w=e;w<y;w++)
#define ff(w,e,y) for(ll w=e;w<=y;w++)
#define mem(x,y) memset(x,y,sizeof(x))

using namespace std;

ll a[100004],s[100004];

int main()
{
    ll n,m,k;

    cin>>n>>k>>m;

    string st;

    cin>>st;

    a[0]=0;
    s[0]=0;

    ff(i,1,n)
    {
        ll g=st[i-1]-'0';

        a[i]=a[i-1];

        if(i%k==0)
        {
            if(g==1)
                a[i]++;

        }
        s[i]=s[i-1]+g;
    }

    ll l,r;
//
//    for(ll i=1;i<=n;i++)
//        cout<<a[i]<<" ";cout<<endl;
//    for(ll i=1;i<=n;i++)
//        cout<<s[i]<<" ";cout<<endl;

    ff(i,1,m)
    {
        cin>>l>>r;

        if(l!=r)
        {
            ll ans=0;

            ll f=r/k;

            ll d=(l-1)/k;

            ll t=f-d;

//            cout<<"t="<<t<<endl;

            ll q=a[r]-a[l-1];

            if(q<t)
            {
                ans+=(t-q);
            }
//            else if(t>q)
//                ans+=(q-t);

            ll qq=s[r]-s[l-1];

            ll ss=qq-q;

            if(ss>0)
                ans+=ss;
            cout<<ans<<endl;
        }
        else
        {
            if(k==1)
            {
                if(st[r-1]=='1')
                    cout<<"0"<<endl;
                else
                    cout<<"1"<<endl;
            }
            else
                cout<<"0"<<endl;
        }
    }
//    main();
    return 0;

}