#include #include #include using namespace std; #include // range set range sum constexpr int md = 998244353; using S = pair; // (sum, size) using F = int; S op(S a, S b) { return {(a.first + b.first) % md, a.second + b.second}; } S e() { return {0, 0}; } S mapping(F f, S x) { return f == 0 ? x : S(x.second * (long long)f % md, x.second); } F composition(F f, F g) { return f == 0 ? g : f; } F id() { return 0; } using LST = atcoder::lazy_segtree; int main() { cin.tie(nullptr), ios::sync_with_stdio(false); vector> maxi, mini; maxi.emplace_back(1 << 30, -1); mini.emplace_back(0, -1); long long ret = 0; int N; cin >> N; vector init(N, {0, 1}); LST mintree(init), maxtree(init); long long ans = 0; for (int i = 0; i < N; ++i) { int a; cin >> a; ret += (long long)a * a % md; { int r = i; while (maxi.back().first <= a) { int l = maxi.back().second; ret += (long long)(a - maxi.back().first) * mintree.prod(l, r).first % md; r = l; maxi.pop_back(); } maxi.emplace_back(a, r); maxtree.apply(r, i + 1, a); } { int r = i; while (mini.back().first >= a) { const int l = mini.back().second; ret += (long long)(a - mini.back().first) * maxtree.prod(l, r).first % md; r = l; mini.pop_back(); } mini.emplace_back(a, r); mintree.apply(r, i + 1, a); } ans += ret % md; } cout << ans % md << '\n'; }