object Main extends App {
  val Array(_, numFires) = io.StdIn.readLine().split(' ').map(_.toLong)
  val candles = io.StdIn.readLine().split(' ').map(_.toLong)

  val distanceCounter = new DistanceCounter
  println(distanceCounter.countMinDistance(candles, numFires))
}


class DistanceCounter {
  
  def countMinDistance(candlePositions: Seq[Long], numFires: Long): Long = {
    var negatives: List[Long] = Nil
    var positives: List[Long] = Nil

    for(position <- candlePositions) {
      if (position < 0) negatives = position :: negatives
      else positives = position :: positives
    }
    positives = positives.reverse

    return foo(Nil, negatives, positives, numFires)

  }

  private def foo(result: List[Long], negatives: Seq[Long], positives: Seq[Long], numFires: Long): Long = {
    if(result.length == numFires) calcDistance(result.reverse)
    else
      Math.min(
        if (negatives.isEmpty) Long.MaxValue else foo(negatives.head :: result , negatives.tail , positives      , numFires) ,
        if (positives.isEmpty) Long.MaxValue else foo(positives.head :: result , negatives      , positives.tail , numFires) ,
        )
  }

  private def calcDistance(routes: Seq[Long]): Long = {
    var currentPosition = 0L
    var distance = 0L
    for(position <- routes) {
      distance = distance + Math.abs(position - currentPosition)
      currentPosition = position
    }
    distance
  }

}
