#include namespace { #pragma GCC diagnostic ignored "-Wunused-function" #include #pragma GCC diagnostic warning "-Wunused-function" using namespace std; using namespace atcoder; #define rep(i,n) for(int i = 0; i < (int)(n); i++) #define rrep(i,n) for(int i = (int)(n) - 1; i >= 0; i--) #define all(x) begin(x), end(x) #define rall(x) rbegin(x), rend(x) template bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; } else return false; } template bool chmin(T& a, const T& b) { if (b < a) { a = b; return true; } else return false; } using ll = long long; using P = pair; using VI = vector; using VVI = vector; using VL = vector; using VVL = vector; using mint = modint998244353; struct S { mint c, x, y, xy; }; S op(S x, S y) { return {x.c + y.c, x.x + y.x, x.y + y.y, x.xy + y.xy}; } S e() { return {}; } struct F { int x, y; }; F id() { return {-1, -1}; } F composition(F f, F g) { F h; h.x = f.x == -1 ? g.x : f.x; h.y = f.y == -1 ? g.y : f.y; return h; } S mapping(F f, S x) { if (f.x != -1) { mint v = f.x; x.x = v * x.c; x.xy = v * x.y; } if (f.y != -1) { mint v = f.y; x.y = v * x.c; x.xy = v * x.x; } return x; } } int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; VI a(n); rep(i, n) cin >> a[i]; lazy_segtree seg(n); VI stmx{-1}, stmn{-1}; mint x2, y2, ans; rep(i, n) { seg.set(i, S{1, 0, 0, 0}); while (stmx.back() != -1 && a[stmx.back()] < a[i]) { int p = stmx.back(); stmx.pop_back(); int q = stmx.back(); x2 -= mint(a[p]).pow(2) * (p - q); } { int p = stmx.back(); x2 += mint(a[i]).pow(2) * (i - p); seg.apply(p + 1, i + 1, F{a[i], -1}); } stmx.emplace_back(i); while (stmn.back() != -1 && a[stmn.back()] > a[i]) { int p = stmn.back(); stmn.pop_back(); int q = stmn.back(); y2 -= mint(a[p]).pow(2) * (p - q); } { int p = stmn.back(); y2 += mint(a[i]).pow(2) * (i - p); seg.apply(p + 1, i + 1, F{-1, a[i]}); } stmn.emplace_back(i); ans += x2 - 2 * seg.all_prod().xy + y2; } cout << ans.val() << '\n'; }