Connection: codeforces 442c Artem and array
The following figure shows an array. Each time a number is deleted, the score for deleting a number is the minimum value of the number on both sides. If either of the two sides does not exist, the score is 0. Ask the maximum score.
Solution: first, remove the continuous A, B, C, A> B & C> B and get min (a, B) points, in this way, the array is converted into a sequence with a descending order. Except for the largest and second largest numbers, other numbers can be scored.
Example: 4 10 2 2 8
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;typedef long long ll;const int N = 5 * 1e5 + 5;int n, c = -1;ll stack[N];int main () { ll x, ans = 0; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%lld", &x); while (c > 0 && stack[c-1] >= stack[c] && stack[c] < x) { ans += min(stack[c-1], x); c--; } stack[++c] = x; } sort (stack, stack + c + 1); for (int i = 0; i <= c - 2; i++) ans += stack[i]; printf("%lld\n", ans); return 0;}