## https://yukicoder.me/problems/no/1715 from collections import deque def check(N, D, pq, border): # 料理に対するborderを求める borders = [] for i, (p, q) in enumerate(pq): borders.append((border + p, i)) borders.sort(reverse=True, key=lambda x: x[0]) dp = [[-float("inf")] * (N + 1) for _ in range(D + 1)] dp[0][0] = 0 for d in range(1, D + 1): array = [(i, dp[d - 1][i]) for i in range(N + 1)] array.sort(reverse=True, key=lambda x: x[1]) ind = 0 queue = deque() for b, i in borders: while ind < N + 1 and array[ind][1] >= b: if len(queue) == 0 or array[ind][1] > queue[0][1]: queue.appendleft(array[ind]) else: while len(queue) > 1 and queue[-1][1] < array[ind][1]: queue.pop() queue.append(array[ind]) ind += 1 if len(queue) == 0: continue elif len(queue) == 1: if queue[0][0] != i + 1: dp[d][i + 1] = queue[0][1] + pq[i][1] - pq[i][0] else: if queue[0][0] != i + 1: dp[d][i + 1] = queue[0][1] + pq[i][1] - pq[i][0] else: dp[d][i + 1] = queue[1][1] + pq[i][1] - pq[i][0] ans = -float("inf") for i in range(N + 1): ans = max(dp[D][i], ans) return ans != - float("inf") def main(): N, D = map(int, input().split()) pq = [] for _ in range(N): p, q = map(int, input().split()) pq.append((p, q)) low = -10 ** 9 high = 10 ** 9 while high - low > 1: mid = (low + high) // 2 if check(N, D, pq, mid): low = mid else: high = mid if check(N, D, pq, high): print(high) else: print(low) if __name__ == "__main__": main()