let rec take n xs =
    match xs with
    | x :: xs' when n > 0 -> x :: take (n - 1) xs'
    | _ -> []

let rec cost k cs xs y =
    let cs' = take k cs in
    let xs' = take k xs in
    List.fold_left2 (fun m c x -> min m (c + abs (y - x))) max_int cs' xs'

let rec solve k cs xs ys =
    match ys with
    | y :: ys' ->
            let c = cost k cs xs y in
            solve k (c :: cs) (y :: xs) ys'
    | [] -> List.hd cs

let () =
    let k =
        let line = read_line () in
        Scanf.sscanf line "%d %d" (fun _ k -> k)
    in
    let h =
        read_line ()
        |> Str.split (Str.regexp " ")
        |> List.map int_of_string
    in
    match h with
    | x :: xs ->
            print_int (solve k [0] [x] xs);
            print_newline ()
    | _ -> ()
