type
aim=^bead;
bead=record
data:integer;
f:aim;
b:aim;
end;
var
a:array[1..100] of bead;
b:array[1..100] of integer;
c:array[1..100] of integer;
n,i,j,s,temp:integer;
p:^bead;
begin
writeln('Input the number of beads');
read(n);
for i:=1 to n do
begin
new(a[i].f);new(a[i].b);
end;
writeln('Input the value of each bead');
for i:=1 to n do
begin
read(a[i].data);
a[i].f:=a[(i-1) mod n]^;
a[i].b:=a[(i+1) mod n]^;
b[i]:=a[i];
c[i]:=i;
end;
for i:=1 to n-1 do
for j:=i to n do
begin
if b[j]<b[i] then
begin
temp:=b[j];b[j]:=b[i];b[i]:=temp;
temp:=c[j];c[j]:=c[i];c[i]:=temp;
end;
end;
s:=0;
for i:=1 to n-1 do
begin
s:=s+a[i].data*a[i].f.data*a[i].b.data;
a[c[i]].b.f:=a[c[i]].f^;a[c[i]].f.b:=a[c[i]].b^;
dispose(a[c[i]].f);dispose(a[c[i]].b);
end;
writeln;
write('The max=',s);
end.