description: Alice has an integer sequence a of length n and all elements are different. She will choose a subsequence of a of length m, and defines the value of a subsequence a_{b_1},a_{b_2},…,a_{b_m} as $$$∑_{i = 1}^m (m ⋅ a_{b_i}) - ∑_{i = 1}^m ∑_{j = 1}^m f(min(b_i, b_j), max(b_i, b_j)), where f(i, j) denotes \min(a_i, a_{i + 1}, \ldots, a_j)$$$.
  
  Alice wants you to help her to maximize the value of the subsequence she choose.
  
  A sequence s is a subsequence of a sequence t if s can be obtained from t by deletion of several (possibly, zero or all) elements.
  
  Input
  
  The first line contains two integers n and m (1 ≤ m ≤ n ≤ 4000).
  
  The second line contains n distinct integers a_1, a_2, …, a_n (1 ≤ a_i < 2^{31}).
  
  Output
  
  Print the maximal value Alice can get.
  
  Examples
  
  Input
  
  
  6 4
  15 2 18 12 13 4
  
  
  Output
  
  
  100
  
  
  Input
  
  
  11 5
  9 3 7 1 8 12 10 20 15 18 5
  
  
  Output
  
  
  176
  
  
  Input
  
  
  1 1
  114514
  
  
  Output
  
  
  0
  
  
  Input
  
  
  2 1
  666 888
  
  
  Output
  
  
  0
  
  Note
  
  In the first example, Alice can choose the subsequence [15, 2, 18, 13], which has the value 4 ⋅ (15 + 2 + 18 + 13) - (15 + 2 + 2 + 2) - (2 + 2 + 2 + 2) - (2 + 2 + 18 + 12) - (2 + 2 + 12 + 13) = 100. In the second example, there are a variety of subsequences with value 176, and one of them is [9, 7, 12, 20, 18].
solution: #include <bits/stdc++.h>
  using namespace std;
  const int MAXN = 4e3 + 5;
  int m;
  int a[MAXN];
  vector<int> g[MAXN];
  int siz[MAXN];
  long long f[MAXN][MAXN];
  void dfs_f(int u, int fa) {
    siz[u] = 1;
    f[u][0] = 0;
    f[u][1] = (long long)(m - 1) * a[u];
    for (int v : g[u])
      if (v != fa) {
        dfs_f(v, u);
        static long long nf[MAXN];
        memset(nf, 0xc0, (siz[u] + siz[v] + 1) << 3);
        for (int i = 0; i <= siz[u]; ++i)
          for (int j = 0; j <= siz[v]; ++j)
            nf[i + j] = max(nf[i + j], f[u][i] + f[v][j] - 2ll * i * j * a[u]);
        siz[u] += siz[v];
        memcpy(f[u], nf, (siz[u] + 1) << 3);
      }
  }
  int main(void) {
    int n;
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
    for (int i = 1; i <= n; ++i) g[i].resize(2);
    stack<int> sta;
    int rt = 0;
    for (int i = 1; i <= n; ++i) {
      while (sta.size() && a[sta.top()] > a[i]) g[i][0] = sta.top(), sta.pop();
      if (sta.size())
        g[sta.top()][1] = i;
      else
        rt = i;
      sta.push(i);
    }
    for (int i = 1; i <= n; ++i)
      for (int j = 0; j < (int)g[i].size(); ++j)
        if (!g[i][j]) {
          g[i].erase(g[i].begin() + j);
          --j;
        }
    dfs_f(rt, 0);
    printf("%lld", f[rt][m]);
    return 0;
  }
  