n, k = map(int, input().split())
a = map(int, input().split())
pos = dict()
for idx, val in enumerate(a):
if val not in pos:
pos[val] = []
pos[val].append(idx)
ans = 0
dp = [0 for _ in range(n)]
for j in range(k - 1, 0, -1):
mx1 = max([dp[i] - i for i in pos[j + 1]], default=-10**9)
mx2 = max([dp[i] + i for i in pos[j + 1]], default=-10**9)
for i in pos[j]:
dp[i] = max(i + mx1, mx2 - i)
if j == 1:
ans = max(ans, dp[i])
print(ans)