#include using namespace std; #define sz(x) (int)(x).size() #define rep(i, l, r) for (int i = l; i < (r); i++) #define all(x) begin(x), end(x) typedef long long ll; typedef vector vi; typedef vector> vii; template ostream &operator<< (ostream& os, const vector &v){ rep(i, 0, sz(v)) { os << v[i]; if (i < sz(v)-1)os << " "; } return os; } template ostream &operator<< (ostream& os, const pair &p){ os << "(" << p.first << ", " << p.second << ") "; return os; } void out(){ cout << endl; } template void out(vector x) { for (int i = 0; i < sz(x); i++) cout << x[i] << " \n"[i == sz(x) - 1]; } template void out(pair x){ cout << "(" << x.first << ", " << x.second << ") ";} template void out(set x) { for (auto y: x) cout << y << " "; cout << endl; } template void out(Head h, Tail ...t) { cout << h << " "; out(t...); } template void chmin(T &a, const T x) { a = min(a, x); } using pii = pair; #include #include using mint = atcoder::modint998244353; void solve() { int n;cin >> n; vector a(n);rep(i, 0, n) cin >> a[i]; struct S{ mint AB, A, B, cnt; }; auto op = [&](S x, S y)->S { return {x.AB + y.AB, x.A + y.A, x.B + y.B, x.cnt + y.cnt}; }; auto e = [&] { return S{0, 0, 0, 0}; }; struct F { mint x, y; }; auto mapping = [&](F f, S x)->S { return {x.AB + f.y * x.A + f.x * x.B + f.x * f.y * x.cnt, x.A + f.x * x.cnt, x.B + f.y * x.cnt, x.cnt}; }; auto composition = [&](F f, F g) -> F { return {f.x + g.x, f.y + g.y}; }; auto id = [&]->F { return {0, 0}; }; atcoder::lazy_segtree seg(vector(n, {0,0,0,1})); stack stmin, stmax;stmin.push(-1);stmax.push(-1); mint ans = 0; rep(i, 0, n) { while (stmin.top() != -1 && a[stmin.top()] >= a[i]) { int r = stmin.top();stmin.pop(); int l = stmin.top(); seg.apply(l+1, r+1, {-a[r], 0}); } int l = stmin.top(); seg.apply(l+1, i+1, {a[i], 0}); stmin.push(i); while (stmax.top() != -1 && a[stmax.top()] <= a[i]) { int r = stmax.top();stmax.pop(); int l = stmax.top(); seg.apply(l+1, r+1, {0, -a[r]}); } l = stmax.top(); seg.apply(l+1, i+1, {0, a[i]}); stmax.push(i); ans += seg.prod(0, i+1).AB; } cout << ans.val() << endl; } int main() { std::cin.tie(0)->sync_with_stdio(0); int T = 1; while (T--)solve(); }