import typing class FenwickTree: '''Reference: https://en.wikipedia.org/wiki/Fenwick_tree''' def __init__(self, n: int = 0) -> None: self._n = n self.data = [0] * n def add(self, p: int, x: typing.Any) -> None: assert 0 <= p < self._n p += 1 while p <= self._n: self.data[p - 1] += x p += p & -p def sum(self, left: int, right: int) -> typing.Any: assert 0 <= left <= right <= self._n return self._sum(right) - self._sum(left) def _sum(self, r: int) -> typing.Any: s = 0 while r > 0: s += self.data[r - 1] r -= r & -r return s n, k = map(int, input().split()) a = list(map(int, input().split())) bit = FenwickTree(n) current = 0 for i in range(n): if i < k: current += abs(a[i] - a[0]) bit.add(i, 1) else: current -= abs(a[i] - a[0]) bit.add(i, -1) minimum = current nextSub = k for i in range(1, n): plus = -bit.sum(i, n) + bit.sum(0, i) current += plus * abs(a[i] - a[i - 1]) while nextSub < n: left = a[nextSub - k] right = a[nextSub] leftDiff = abs(left - a[i]) rightDiff = abs(right - a[i]) if leftDiff > rightDiff: current -= 2 * leftDiff current += 2 * rightDiff bit.add(nextSub, 2) bit.add(nextSub - k, -2) nextSub += 1 else: break minimum = min(minimum, current) print(minimum)