{-# LANGUAGE RecursiveDo        #-}
{-# LANGUAGE BangPatterns       #-}
{-# 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], [Int])
g k (costs, starts) dist = (costs', starts')
  where cost    = minimum $ take k $ zipWith (\ c s -> c + abs (dist - s)) costs starts
        costs'  = cost : costs
        starts' = dist : starts

solve :: Int -> Int -> [Int] -> Int
solve n k h
    | n <= k    = last $ f n h
    | otherwise = head costs
      where (costs, _) = foldl (g k) (reverse $ f k h, reverse $ drop k h) 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
