You are given an array $a_1, a_2, \dots, a_n$ and an integer $k$.

You are asked to divide this array into $k$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $f(i)$ be the index of subarray the $i$-th element belongs to. Subarrays are numbered from left to right and from $1$ to $k$.

Let the cost of division be equal to $\sum\limits_{i=1}^{n} (a_i \cdot f(i))$. For example, if $a = [1, -2, -3, 4, -5, 6, -7]$ and we divide it into $3$ subbarays in the following way: $[1, -2, -3], [4, -5], [6, -7]$, then the cost of division is equal to $1 \cdot 1 - 2 \cdot 1 - 3 \cdot 1 + 4 \cdot 2 - 5 \cdot 2 + 6 \cdot 3 - 7 \cdot 3 = -9$.

Calculate the maximum cost you can obtain by dividing the array $a$ into $k$ non-empty consecutive subarrays. 


-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 3 \cdot 10^5$).

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($ |a_i| \le 10^6$). 


-----Output-----

Print the maximum cost you can obtain by dividing the array $a$ into $k$ nonempty consecutive subarrays. 


-----Examples-----
Input
5 2
-1 -2 5 -4 8

Output
15

Input
7 6
-3 0 -1 -2 -2 -4 -1

Output
-45

Input
4 1
3 -1 6 0

Output
8

Difficulty: HARD
Tags: Sorting

Greedy algorithms
Skill types: Sorting

Greedy algorithms

Starter code:

Solutions:
(n, k) = map(int, input().split())
A = [int(i) for i in input().split()]
suff = []
sumi = 0
for i in range(n - 1, 0, -1):
	sumi += A[i]
	suff.append(sumi)
suff.sort(reverse=True)
ans = sum(suff[:k - 1])
ans += sum(A)
print(ans)


(n, k) = map(int, input().strip().split(' '))
a = list(map(int, input().strip().split(' ')))
cnt = []
cnt.append(a[-1])
for i in range(1, n):
	cnt.append(cnt[i - 1] + a[-(i + 1)])
ans = cnt[-1]
del cnt[-1]
cnt.sort(reverse=True)
ans += sum(cnt[:k - 1])
print(ans)


import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
a = [int(i) for i in input().split()]
acc = [a.pop()]
while a:
	acc.append(a.pop() + acc[-1])
s1 = acc.pop()
acc.sort()
ans = sum(acc[n - k:]) + s1
print(ans)


def main():
	buf = input()
	buflist = buf.split()
	n = int(buflist[0])
	k = int(buflist[1])
	buf = input()
	buflist = buf.split()
	a = list(map(int, buflist))
	a_sum = []
	for i in range(1, len(a) + 1):
		if not a_sum:
			a_sum.append(a[-i])
		else:
			a_sum.append(a[-i] + a_sum[-1])
	cost = a_sum.pop()
	a_sum.sort(reverse=True)
	for i in range(k - 1):
		cost += a_sum[i]
	print(cost)

def __starting_point():
	main()
__starting_point()


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
(n, k) = map(int, input().split())
l = list(map(int, input().split()))
a = [0] * (n - 1)
s = SegmentTree(l)
for i in range(1, n):
	a[i - 1] = s.query(i, n - 1)
a.sort(reverse=True)
print(sum(a[:k - 1]) + sum(l))


(n, k) = [int(i) for i in input().split()]
data = [int(i) for i in input().split()]
newd = [0] * n
newd[-1] = data[-1]
for i in range(n - 2, -1, -1):
	newd[i] = data[i] + newd[i + 1]
a = newd[0]
newd.sort()
if k == 1:
	ans = a
elif newd[n + 1 - k] > a:
	ans = a + sum(newd[n + 1 - k:])
else:
	ans = sum(newd[n - k:])
print(ans)


import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
A = list(map(int, input().split()))
SUM = [0]
for a in A[::-1]:
	SUM.append(SUM[-1] + a)
SUM = SUM[::-1]
ANS = SUM[0]
ANS += sum(sorted(SUM[1:-1], reverse=True)[:k - 1])
print(ANS)


from itertools import accumulate
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
acc = list(accumulate(a))[:-1]
acc.sort()
ans = k * sum(a) - sum(acc[:k - 1])
print(ans)


import heapq
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
for i in range(n - 2, -1, -1):
	a[i] += a[i + 1]
res = a[0] + sum(heapq.nlargest(k - 1, a[1:]))
print(res)


import heapq
(n, k) = list(map(int, input().split()))
a = list(map(int, input().split()))
s = [0 for i in range(n)]
s[0] = a[0]
for i in range(1, n):
	s[i] = s[i - 1] + a[i]
x = s.pop()
x *= k
heapq.heapify(s)
for _ in range(k - 1):
	x -= heapq.heappop(s)
print(x)


(n, k) = map(int, input().split())
nums = list(map(int, input().split()))
suffixSum = [nums[-1]]
for i in nums[-2::-1]:
	suffixSum.append(suffixSum[-1] + i)
suffixSum = suffixSum[:-1]
suffixSum.sort(reverse=True)
ans = sum(nums)
ans += sum(suffixSum[:k - 1])
print(ans)


(N, K) = map(int, input().split())
A = [int(a) for a in input().split()]
B = [0] * N
B[N - 1] = A[N - 1]
for i in range(N - 1)[::-1]:
	B[i] = B[i + 1] + A[i]
print(sum(sorted(B[1:])[::-1][:K - 1]) + B[0])


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
b = [0 for i in range(n)]
for i in range(n - 1, -1, -1):
	if i == n - 1:
		b[i] = a[i]
	else:
		b[i] = b[i + 1] + a[i]
ans = b[0]
b[1:] = sorted(b[1:])
k -= 1
for i in range(n - 1, -1, -1):
	if k == 0:
		break
	ans += b[i]
	k -= 1
print(ans)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
p = [0]
for x in a[::-1]:
	p.append(p[-1] + x)
print(p[-1] + sum(sorted(p[1:-1])[n - k:]))


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
p = [0]
for i in a[::-1]:
	p.append(p[-1] + i)
p = p[::-1]
ans = p[0]
ans += sum(sorted(p[1:-1], reverse=True)[:k - 1])
print(ans)


import sys
from array import array
import typing as Tp

def input():
	return sys.stdin.buffer.readline().decode('utf-8')

def bfs(adj, peoples):
	stack = [0]
	order = []
	parent = [-1] * len(adj)
	subt = peoples[:]
	while stack:
		v = stack.pop()
		order.append(v)
		for dest in adj[v]:
			if parent[v] == dest:
				continue
			parent[dest] = v
			stack.append(dest)
	for v in reversed(order):
		if v != 0:
			subt[parent[v]] += subt[v]
	return (order, subt, parent)

def main():
	from itertools import accumulate
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	acc = list(accumulate(reversed(a)))
	print(acc[-1] + sum(sorted(acc[:-1], reverse=True)[:k - 1]))
main()


import sys
from collections import defaultdict as dd
from collections import deque
from fractions import Fraction as f
from copy import *
from bisect import *
from heapq import *
from itertools import permutations

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')

def li():
	return [int(x) for x in input().split()]

def fi():
	return int(input())

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)

def bo(i):
	return ord(i) - ord('a')
t = 1
while t > 0:
	t -= 1
	(n, k) = mi()
	a = li()
	suf = [0]
	for i in range(n - 1, -1, -1):
		suf.append(suf[-1] + a[i])
	suf = suf[1:]
	c = suf[-1] + sum(sorted(suf[:n - 1], reverse=True)[:k - 1])
	print(c)


from collections import defaultdict as dd
import math

def nn():
	return int(input())

def li():
	return list(input())

def mi():
	return list(map(int, input().split()))

def lm():
	return list(map(int, input().split()))
(n, k) = mi()
l = lm()
running = [0] * (n - 1)
for i in range(len(l) - 1):
	if i == 0:
		running[i] = (l[i], i + 1)
	else:
		running[i] = (running[i - 1][0] + l[i], i + 1)
running.sort()
sliced = running[:k - 1]
sliced.sort(key=lambda x: x[1])
cost = 0
last = 0
for i in range(len(sliced)):
	cost += (i + 1) * sum(l[last:sliced[i][1]])
	last = sliced[i][1]
cost += k * sum(l[last:])
print(cost)


import sys

class Main:

	def __init__(self):
		self.buff = None
		self.index = 0

	def next(self):
		if self.buff is None or self.index == len(self.buff):
			self.buff = self.next_line()
			self.index = 0
		val = self.buff[self.index]
		self.index += 1
		return val

	def next_line(self):
		return sys.stdin.readline().split()

	def next_ints(self):
		return [int(x) for x in sys.stdin.readline().split()]

	def next_int(self):
		return int(self.next())

	def solve(self):
		(n, k) = self.next_ints()
		x = self.next_ints()
		ss = []
		s = 0
		for a in x[::-1]:
			s += a
			ss.append(s)
		ss = sorted(ss[:-1], reverse=True)
		print(s + sum(ss[:k - 1]))
Main().solve()


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class SegmentTree:

	def __init__(self, data, default=-10 ** 6, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree1:

	def __init__(self, data, default=10 ** 6, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
MOD = 10 ** 9 + 7

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(50001)]
pp = []

def SieveOfEratosthenes(n=50000):
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	for i in range(50001):
		if prime[i]:
			pp.append(i)
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
suff = [0] * n
suff[-1] = a[-1]
for i in range(n - 2, -1, -1):
	suff[i] = suff[i + 1] + a[i]
s = sum(a)
suff = suff[1:]
suff.sort(reverse=True)
for i in range(k - 1):
	s += suff[i]
print(s)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
if n == 1:
	print(a[0])
else:
	p = [a[-1]] + [0] * (n - 2)
	for i in range(n - 2):
		p[i + 1] = p[i] + a[-i - 2]
	j = p[-1] + a[0]
	p.sort(reverse=True)
	print(j + sum(p[:k - 1]))


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
from fractions import Fraction
import heapq as hp
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
(n, k) = Ri()
a = Ri()
suffix = [0] * n
suffix[n - 1] = a[n - 1]
for i in range(len(a) - 2, -1, -1):
	suffix[i] = suffix[i + 1] + a[i]
suffix = suffix[1:]
suffix.sort(reverse=True)
summ = sum(a)
for i in range(k - 1):
	summ += suffix[i]
print(summ)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
a = a[::-1]
s = [a[0]]
S = 0
for x in a[1:]:
	s.append(s[-1] + x)
S += s[-1]
s.pop()
k -= 1
s = sorted(s)
i = 0
while i <= k - 1:
	S += s.pop()
	i += 1
print(S)


from collections import Counter, OrderedDict
from itertools import permutations as perm
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
import math
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1000000000.0) + 7
inf = float('inf')
(n, k) = gil()
a = gil()
for i in range(1, n):
	a[i] += a[i - 1]
ans = a.pop()
a.sort()
print(k * ans - sum(a[:k - 1]))


import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
s = 0
p = []
for i in range(n - 1, 0, -1):
	s += a[i]
	p.append(s)
p.sort()
p.reverse()
res = s + a[0]
for i in range(k - 1):
	res += p[i]
print(res)


from sys import stdin, stdout
(N, K) = [int(x) for x in stdin.readline().split()]
arr = [int(x) for x in stdin.readline().split()]
if K == 1:
	print(sum(arr))
	quit()
cum = [0] * N
s = 0
for i in range(N - 1, -1, -1):
	s += arr[i]
	cum[i] = s
tmp = cum[0]
A = sorted(cum[1:], reverse=True)
res = tmp
for i in range(K - 1):
	res += A[i]
print(res)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
s = [0 for i in range(n)]
for i in range(n - 1, -1, -1):
	s[i] = a[i] if i == n - 1 else a[i] + s[i + 1]
s0 = s[0]
s1 = s[1:]
s1.sort()
res = 0
for i in range(n - 2, n - k - 1, -1):
	res += s1[i]
print(res + s0)


import sys

def main():
	(n, k) = [int(x) for x in sys.stdin.readline().split(' ')]
	a = [int(x) for x in sys.stdin.readline().split(' ')]
	suffix = []
	if n == k:
		return sum((elem * (i + 1) for (i, elem) in enumerate(a)))
	c = 0
	for i in range(n - 1, 0, -1):
		c += a[i]
		suffix.append(c)
	suffix.sort(key=lambda x: x)
	suffix.reverse()
	return sum(suffix[:k - 1]) + sum(a)
print(main())


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
prefix_sum = [0]
for t in a:
	prefix_sum.append(prefix_sum[-1] + t)
sk = prefix_sum[-1]
prefix_sum = sorted(prefix_sum[1:-1])
print(k * sk - sum(prefix_sum[:k - 1]))


def gns():
	return list(map(int, input().split()))
(n, k) = gns()
ns = gns()
sm = [ns[-1]]
for i in reversed(range(n - 1)):
	sm.append(sm[-1] + ns[i])
ans = sm.pop()
sm.sort()
if k > 1:
	ans += sum(sm[-k + 1:])
print(ans)


import sys, io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(n, k) = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
suff = [0] * n
suff[-1] = a[-1]
for i in range(n - 2, -1, -1):
	suff[i] = suff[i + 1] + a[i]
ans = suff[0]
suff = suff[1:]
suff.sort(reverse=1)
ans += sum(suff[:k - 1])
print(ans)


(n, k) = list(map(int, input().split()))
a = list(map(int, input().split()))
ruiseki = [0] * (n + 1)
ans = 0
for i in range(n):
	ruiseki[i + 1] = ruiseki[i] + a[i]
bb = sorted(ruiseki[1:n])
ans += ruiseki[-1] * k
for i in range(k - 1):
	ans -= bb[i]
print(ans)


import sys
(n, k) = map(int, input().split())
nums = list(map(int, input().split()))
suffixSum = [nums[-1]]
for val in nums[-2::-1]:
	suffixSum.append(suffixSum[-1] + val)
ans = suffixSum[-1]
suffixSum = suffixSum[:-1]
suffixSum.sort(reverse=True)
ans += sum(suffixSum[:k - 1])
print(ans)


from sys import stdin, stdout
from itertools import combinations
from collections import defaultdict, OrderedDict
import math
import heapq

def listIn():
	return list(list(map(int, stdin.readline().strip().split())))

def stringListIn():
	return [x for x in stdin.readline().split()]

def intIn():
	return int(stdin.readline())

def stringIn():
	return stdin.readline().strip()

def __starting_point():
	(n, k) = listIn()
	a = listIn()
	arr = [a[0]] + [0] * (n - 1)
	for i in range(1, n):
		arr[i] = arr[i - 1] + a[i]
	max_cost = arr[n - 1] * k
	b = sorted(arr[:n - 1])
	for i in range(k - 1):
		max_cost -= b[i]
	print(max_cost)
__starting_point()


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
for i in range(n - 2, -1, -1):
	a[i] += a[i + 1]
ans = a.pop(0)
a.sort(reverse=True)
print(ans + sum(a[:k - 1]))


import sys, math

def read_int():
	return int(sys.stdin.readline().strip())

def read_int_list():
	return list(map(int, sys.stdin.readline().strip().split()))

def read_string():
	return sys.stdin.readline().strip()

def read_string_list(delim=' '):
	return sys.stdin.readline().strip().split(delim)
(n, k) = read_int_list()
arr = read_int_list()
for i in range(n - 2, -1, -1):
	arr[i] += arr[i + 1]
ans = arr[0]
arr.pop(0)
arr.sort(reverse=True)
ans += sum(arr[:k - 1])
print(ans)


import math
(n, k) = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
b = []
a.reverse()
counter = 0
for i in range(n - 1):
	counter += a[i]
	b.append(counter)
b.sort(reverse=True)
print(sum(b[:k - 1]) + sum(a))


import sys

def input():
	return sys.stdin.readline().rstrip()
DXY = [(0, -1), (1, 0), (0, 1), (-1, 0)]

def main():
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	for i in range(1, n):
		a[i] += a[i - 1]
	ans = k * a[n - 1]
	a.pop()
	a.sort()
	for i in range(k - 1):
		ans -= a[i]
	print(ans)
	return 0
main()


import sys, os, io
from sys import stdin
from math import log, gcd, ceil
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import math
alphabets = list('abcdefghijklmnopqrstuvwxyz')

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(int(i))
			n = n / i
	if n > 2:
		l.append(n)
	return list(set(l))

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def si():
	return input()

def prefix_sum(arr):
	r = [0] * (len(arr) + 1)
	for (i, el) in enumerate(arr):
		r[i + 1] = r[i] + el
	return r

def divideCeil(n, x):
	if n % x == 0:
		return n // x
	return n // x + 1

def ii():
	return int(input())

def li():
	return list(map(int, input().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(''.join([str(x) for x in a]) + '\n')
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = 1
for _ in range(t):
	(n, k) = li()
	a = li()
	suf = []
	cur = 0
	for i in range(n - 1, -1, -1):
		cur += a[i]
		suf.append(cur)
	ans = suf[-1]
	suf = suf[::-1]
	suf = suf[1:]
	suf.sort(reverse=True)
	for i in range(k - 1):
		ans += suf[i]
	print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def main():
	(n, k) = RL()
	arr = RLL()
	res = [0]
	for i in range(n - 1, -1, -1):
		res.append(res[-1] + arr[i])
	ret = sorted(res[1:-1], reverse=1)
	print(sum(ret[:k - 1]) + res[-1])
main()


def __starting_point():
	(n, k) = map(int, input().split())
	aa = list(map(int, input().split()))
	ss = [0]
	for a in reversed(aa):
		ss.append(ss[-1] + a)
	ss = ss[1:]
	if k == 1:
		print(ss[-1])
		return
	print(ss[-1] + sum(sorted(ss[:-1])[-(k - 1):]))
__starting_point()


(N, K) = map(int, input().split())
A = list(map(int, input().split()))
L = [0]
for i in A[::-1]:
	L.append(L[-1] + i)
k = L[-1] + sum(sorted(L[1:-1])[N - K:])
print(k)


li = input().split()
n = int(li[0])
k = int(li[1])
a = input().split()
for i in range(n):
	a[i] = int(a[i])
for i in range(n - 2, -1, -1):
	a[i] += a[i + 1]
sa = sorted(a[1:])
ans = a[0]
for i in range(k - 1):
	ans += sa[n - 2 - i]
print(ans)


import sys
(n, k) = list(map(int, sys.stdin.readline().strip().split()))
a = list(map(int, sys.stdin.readline().strip().split()))
L = [a[-1]] * n
for i in range(1, n):
	L[i] = L[i - 1] + a[n - i - 1]
x = L.pop()
L.sort()
for i in range(0, k - 1):
	x = x + L[n - 2 - i]
print(x)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
b = []
s = 0
for x in a[::-1]:
	s += x
	b.append(-s)
if k == 1:
	print(-b[-1])
else:
	d = sorted(b[:-1])
	print(-sum(d[:k - 1]) - b[-1])


(n, k) = map(int, input().split())
mass = [int(i) for i in input().split()]
mass = mass[::-1]
summ = 0
m = []
for i in range(n - 1):
	summ += mass[i]
	m.append(summ)
m = sorted(m, reverse=True)
print(sum(mass) + sum(m[:k - 1]))


(n, k) = map(int, input().split())
arr = reversed(list(map(int, input().split())))
sum = 0
suff = []
for x in arr:
	sum += x
	suff.append(sum)
suff.pop()
ans = sum
suff = sorted(suff, reverse=True)
for i in range(k - 1):
	ans += suff[i]
print(ans)


import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
s = [a[-1]]
for i in range(n - 2, -1, -1):
	s.append(s[-1] + a[i])
(a, s) = (s[-1], s[:-1])
s.sort()
if k > 1:
	print(a + sum(s[1 - k:]))
else:
	print(a)


(n, k) = [int(i) for i in input().split()]
array = [int(i) for i in input().split()]
summ = 0
sums_array = []
for i in range(len(array) - 1, 0, -1):
	summ += array[i]
	sums_array.append(summ)
sorted_sums = sorted(sums_array, reverse=True)
a = sorted_sums[:k - 1]
full_sum = sum(array) + sum(sorted_sums[:k - 1])
print(full_sum)


(n, k) = map(int, input().split())
aa = list(map(int, input().split()))
ss = [0]
for a in reversed(aa):
	ss.append(ss[-1] + a)
ss = ss[1:]
if k == 1:
	print(ss[-1])
	exit(0)
print(ss[-1] + sum(sorted(ss[:-1])[-(k - 1):]))


import sys
input = sys.stdin.readline
(N, K) = map(int, input().split())
A = list(map(int, input().split()))
s = 0
B = []
for i in reversed(range(N)):
	s += A[i]
	B.append(s)
ans = B.pop()
B.sort(reverse=True)
for i in range(K - 1):
	ans += B[i]
print(ans)