(N,K),P,C = $<.map{|ln| ln.split.map(&:to_i) }

Max = lambda{|a,k|
	k = a.size if a.size<k
	next 0 if k <= 0

	l = r = 1-k
	max = sum = a[l]
	while r+1 < a.size
		sum += a[r+=1]
		sum += a[r+=1] while r+1 < a.size && r+1 < l+k && 0<=a[r+1]
		max = sum if max < sum && r-l < k
		sum -= a[-1+l+=1]
		sum -= a[-1+l+=1] while l<r && a[l]<=0
		max = sum if max < sum
	end
	next max
}

A = P.map{|p|
	a,f = [],lambda{|p|
		a << C[p-1]
		C[p-1] = nil
		next P[p-1]
	}
	q = f[p]
	next unless a[0]
	q = f[q] until q == p
	next a
}.compact

p A.map{|a|
	s = a.sum
	s < 0 ? Max[a,K] : s*[K/a.size-1,0].max + [s+Max[a,K%a.size],Max[a,K]].max
}.max
