PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FT0000105. Tổng lớn nhất của dãy con cân bằng (Maximum Balanced Subsequence Sum)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Tổng lớn nhất của dãy con cân bằng (Maximum Balanced Subsequence Sum)

Maximum Balanced Subsequence Sum

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

You are given an integer sequence a1,a2,…,ana_1,a_2,\ldots,a_n whose positions are numbered 11 through nn. A nonempty subsequence selects indices i1<i2<⋯<iki_1<i_2<\cdots<i_k.

It is called balanced if, for every two consecutive selected indices it−1<iti_{t-1}<i_t, the following inequality holds:

ait−ait−1≥it−it−1.a_{i_t}-a_{i_{t-1}}\ge i_t-i_{t-1}.

Every one-element subsequence is considered balanced. The sum of a subsequence is the sum of the values at its selected positions. Find the maximum sum of any nonempty balanced subsequence. Values may be negative, so the answer may also be negative.

Input

  • The first line contains integer nn, the sequence length.
  • The second line contains nn integers a1,a2,…,ana_1,a_2,\ldots,a_n in order.

Output

Print one integer: the maximum possible sum of a nonempty balanced subsequence.

Subtasks

  • Subtask 1 (20 points): 1≤n≤201\le n\le 20; −109≤ai≤109-10^9\le a_i\le 10^9 for every 1≤i≤n1\le i\le n.
  • Subtask 2 (30 points): 1≤n≤30001\le n\le 3000; −109≤ai≤109-10^9\le a_i\le 10^9 for every 1≤i≤n1\le i\le n.
  • Subtask 3 (50 points): 1≤n≤1000001\le n\le 100000; −109≤ai≤109-10^9\le a_i\le 10^9 for every 1≤i≤n1\le i\le n.

Examples

Example 1

Input

4
3 3 5 6

Output

14

Explanation

For (3,3,5,6)(3,3,5,6), select indices (1,3,4)(1,3,4), giving values (3,5,6)(3,5,6). From positions 11 to 33, 5−3=2≥3−1=25-3=2\ge3-1=2; from positions 33 to 44, 6−5=1≥4−3=16-5=1\ge4-3=1. The sum is 3+5+6=143+5+6=14. Indices (2,3,4)(2,3,4) also achieve 1414. The two values 33 cannot both be selected since their difference 00 is smaller than their index gap 11. The maximum is 14.

Example 2

Input

2
-2 -1

Output

-1

Explanation

Selecting position 11 alone gives sum −2-2, and position 22 alone gives sum −1-1. Selecting both is balanced because −1−(−2)=1≥1-1-(-2)=1\ge1, but its sum is −3-3. The maximum of −2,−1,−3-2,-1,-3 is −1-1, so print -1.