{-# LANGUAGE RecursiveDo        #-}
{-# LANGUAGE OverloadedStrings  #-}
{-# LANGUAGE NumericUnderscores #-}

import qualified Data.ByteString.Char8 as C8
import Data.List
import Data.Char

f :: Int -> [Int] -> [Int]
f k hs@(h:_) = map (abs . subtract h) (take k hs)

g :: Int -> [Int] -> [Int] -> [Int] -> Int
g _ costs _      []                  = head costs
g k costs starts dists@(dist:dists') = g k costs' starts' dists'
  where cost    = minimum $ zipWith (\ c s -> c + abs (dist - s)) costs starts
        costs'  = cost : take (k - 1) costs
        starts' = dist : take (k - 1) starts

solve :: Int -> Int -> [Int] -> Int
solve n k h
    | n > k     = g k (reverse $ f k h) (reverse $ take k h) (drop k h)
    | otherwise = last $ f n h

main = do
  [n, k] <- unfoldr (C8.readInt . C8.dropWhile isSpace) <$> C8.getLine
  h      <- unfoldr (C8.readInt . C8.dropWhile isSpace) <$> C8.getLine
  print $ solve n k h
