直接上代码
program seq;
const maxn=100000+10;
var
a,f,g,f1,f2:array[0..maxn]of int64;
i,j,n:longint; ans:int64;
function max(i,j:int64):int64;
begin
if i>j then exit(i); exit(j);
end;
function min(i,j:int64):int64;
begin
if i<j then exit(i); exit(j);
end;
begin
readln(n); for i:=1 to n do read(a[i]);
for i:=2 to n-1 do f[i]:=f[i-1]+max(0,a[i-1]-a[i]+1);
for i:=n-1 downto 2 do g[i]:=g[i+1]+max(0,a[i+1]-a[i]+1);
j:=2;
for i:=3 to n-2 do begin
while (j<i-1)and(max(f[j+1]-f[1],g[j+1]-g[i])<=max(f[j]-f[1],g[j]-g[i])) do inc(j);
f1[i]:=max(f[j]-f[1],g[j]-g[i]);
end;
j:=n-1;
for i:=n-2 downto 3 do begin
while (j>i+1)and(max(f[j-1]-f[i],g[j-1]-g[n])<=max(f[j]-f[i],g[j]-g[n])) do dec(j);
f2[i]:=max(f[j]-f[i],g[j]-g[n]);
end;
ans:=f1[3]+f2[3];
for i:=3 to n-2 do ans:=min(ans,f1[i]+f2[i]);
writeln(ans);
end.