import sys # sys.setrecursionlimit(200005) int1 = lambda x: int(x)-1 pDB = lambda *x: print(*x, end="\n", file=sys.stderr) p2D = lambda x: print(*x, sep="\n", end="\n\n", file=sys.stderr) def II(): return int(sys.stdin.readline()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def LI1(): return list(map(int1, sys.stdin.readline().split())) def LLI1(rows_number): return [LI1() for _ in range(rows_number)] def SI(): return sys.stdin.readline().rstrip() dij = [(0, 1), (-1, 0), (0, -1), (1, 0)] # dij = [(0, 1), (-1, 0), (0, -1), (1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)] inf = (1 << 63)-1 # inf = (1 << 31)-1 # md = 10**9+7 md = 998244353 class WaveletMatrix: def __init__(self, aa): self.dec = sorted(set(aa)) self.enc = {a: i for i, a in enumerate(self.dec)} aa = [self.enc[a] for a in aa] self.log = len(self.dec).bit_length() self.n = len(aa) self.bb = [[0] for _ in range(self.log)] for i in range(self.log)[::-1]: naa = [[], []] for a in aa: d = a >> i & 1 naa[d].append(a) self.bb[i].append(self.bb[i][-1]+d) aa = naa[0]+naa[1] self.fi = {} for i in range(self.n)[::-1]: self.fi[aa[i]] = i self.aa = aa def _move(self, i, idx, d): if d: return self.n-self.bb[i][-1]+self.bb[i][idx] return idx-self.bb[i][idx] def __getitem__(self, idx): res = 0 for i in range(self.log)[::-1]: d = self.bb[i][idx+1]-self.bb[i][idx] res |= d << i idx = self._move(i, idx, d) return self.dec[res] # count a in [0,r) def rank(self, a, r): a = self.enc[a] if a not in self.fi: return 0 for i in range(self.log)[::-1]: r = self._move(i, r, a >> i & 1) return r-self.fi[a] # index of ith(0-indexed) a def select(self, a, ith): a = self.enc[a] if a not in self.fi: return -1 idx = self.fi[a]+ith for i in range(self.log-1): d = a >> i & 1 l, r = -1, self.n-1 while l+1 < r: m = (l+r)//2 nxt = self.n-self.bb[i][-1]+self.bb[i][m+1] if d else m+1-self.bb[i][m+1] if nxt < idx+1: l = m else: r = m idx = r return idx # ith value in sorted [l,r) def quantile(self, l, r, ith): for i in range(self.log)[::-1]: c0 = r-l-(self.bb[i][r]-self.bb[i][l]) if c0 > ith: l, r = self._move(i, l, 0), self._move(i, r, 0) else: l, r = self._move(i, l, 1), self._move(i, r, 1) ith -= c0 return self.dec[self.aa[l+ith]] n = II() aa = LI() wm = WaveletMatrix(aa) ans = -inf for k in range(1, n+1): m = (k-1)//2 st = [0] t = 0 for r in range(n, k-1, -k): t += wm.quantile(r-k, r, m)*k st.append(max(t, st[-1])) ans = max(ans, st[-1]) s = 0 for l in range(0, n-k+1, k): s += wm.quantile(l, l+k, m)*k st.pop() ans = max(ans, s+st[-1]) # pDB(k, ans, st) print(ans)