#include using namespace std; #ifdef LOCAL #include "algo/debug.h" #else #define debug(...) (void(0)) #endif #include using mint = atcoder::modint998244353; #include struct S { mint sum, sz; }; S op(S a, S b) { return S{a.sum + b.sum, a.sz + b.sz}; } S e() { return S{0, 0}; } using F = long; F id() { return -1; } S mapping(F f, S x) { if(f == id()) return x; x.sum = f * x.sz; return x; } F composition(F f, F g) { if(f == id()) return g; return f; } void solve() { int N; cin >> N; vector A(N); for(int i = 0; i < N; i++) cin >> A[i]; atcoder::lazy_segtree Max(vector(N, {0, 1})), Min(vector(N, {0, 1})); mint ans = 0; vector> st1; // max vector> st2; // min mint sum = 0; for(int i = 0; i < N; i++) { { int w1 = 1; int cur = i; while(!st1.empty() && st1.back().first <= A[i]) { auto[h, w] = st1.back(); sum += mint(A[i] - h) * Min.prod(cur - w, cur).sum; cur -= w; w1 += w; st1.pop_back(); } st1.push_back({A[i], w1}); Max.apply(i + 1 - w1, i + 1, A[i]); } { int w2 = 1; int cur = i; while(!st2.empty() && st2.back().first >= A[i]) { auto[h, w] = st2.back(); sum -= mint(h - A[i]) * Max.prod(cur - w, cur).sum; cur -= w; w2 += w; st2.pop_back(); } st2.push_back({A[i], w2}); Min.apply(i + 1 - w2, i + 1, A[i]); } ans += sum; mint t = A[i] * A[i]; ans += t; sum += t; } cout << ans.val() << endl; } int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int tt = 1; // std::cin >> tt; while(tt--) { solve(); } }