#include<iostream>
#include<cstdio>
#include<map>
#include<bitset>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<ctime>
using namespace std;
#define M 200005
#define N 1000005
#define MP make_pair
#define debug() cerr<<"Why So Serious?"<<endl
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
template<class T>void Rd(T &x){
	x=0;static char c;
	while(c=getchar(),c<48);
	do x=(x<<1)+(x<<3)+(c^48);
	while(c=getchar(),c>47);
}
int n;
int Id1[M],Id2[M];
int A[M],B[M];
bool cmp1(int a,int b){
	return (A[a]==A[b])?a<b:A[a]<A[b];
}
bool cmp2(int a,int b){
	return (B[a]==B[b])?a<b:B[a]<B[b];
}
int P[M];
int Sum[M];
void Add(int x){
	for(;x>0;x-=x&-x)Sum[x]++;
}
int Query(int x){
	int res=0;
	for(;x<=n;x+=x&-x)res+=Sum[x];
	return res;
}
int main(){
	Rd(n);
	for(int i=1;i<=n;++i)Id1[i]=Id2[i]=i;
	for(int i=1;i<=n;++i)Rd(A[i]),A[i]+=i;
	for(int i=1;i<=n;++i)Rd(B[i]),B[i]+=i;
	sort(Id1+1,Id1+n+1,cmp1);
	sort(Id2+1,Id2+n+1,cmp2);
	ll ans=0;
	for(int i=1;i<=n;++i){
		if(A[Id1[i]]!=B[Id2[i]]){
			puts("-1");
			return 0;
		}
		P[Id1[i]]=Id2[i];
	}
	for(int i=1;i<=n;++i){
		ans+=Query(P[i]);
		Add(P[i]);
	}
	printf("%lld\n",ans);
	return 0;
}
#include <bits/stdc++.h>
using namespace std;

int main() {
	int n,m,a[2200000],mex,nums[2200000];
  vector<int> v;
  cin >> n >> m;
  for(int i=0; i<n; i++) {
    cin >> a[i];
    if(i<m) v.push_back(a[i]);
  }
  sort(v.begin(),v.end());
  int now=0;
  bool ok=true;
  for(int i=0; i<m; i++){
  	if(v[i] == now) now++;
    if(v[i] > now && ok) {
      mex = now;
      ok=false;
    }
    nums[v[i]]++;
  }
  if(ok) mex = now;
  for(int i=0; i<n-m; i++){
  	nums[a[i]]--;
    nums[a[i+m]]++;
    if(a[i] < mex && nums[a[i]]==0) mex = a[i];
  }
  cout << mex;
}