I=lambda:map(int,raw_input().split()) R=range;N,K=I();a=I() c={v:i for i,v in enumerate(sorted(a))} for i in R(N):a[i]=c[a[i]];A=0 for i in R(N): q,r=divmod(a.index(i)-i,K) if r!=0:A=-1;break A+=q for j in R(i+q*K,i,-K):a[j],a[j-K]=a[j-K],a[j] print A