Non-equal Neighbours
You are given an array of $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$. Your task is to calculate the number of arrays of $$$n$$$ positive integers $$$b_1, b_2, \ldots, b_n$$$ such that:   $$$1 \le b_i \le a_i$$$ for every $$$i$$$ ($$$1 \le i \le n$$$), and  $$$b_i \neq b_{i+1}$$$ for every $$$i$$$ ($$$1 \le i \le n - 1$$$). The number of such arrays can be very large, so print it modulo $$$998\,244\,353$$$.
In the first test case possible arrays are $$$[1, 2, 1]$$$ and $$$[2, 1, 2]$$$.In the second test case possible arrays are $$$[1, 2]$$$, $$$[1, 3]$$$, $$$[2, 1]$$$ and $$$[2, 3]$$$.
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the array $$$a$$$.The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).
Print the answer modulo $$$998\,244\,353$$$ in a single line.
import sys
input = sys.stdin.buffer.readline

class SegmentTree:

    def __init__(self, data, default=0, func=max):
        """"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()
        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        """"""
        start += self._size
        stop += self._size
        res_left = res_right = self._default
        while start < stop:
            if start & 1:
                res_left = self._func(res_left, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res_right = self._func(self.data[stop], res_right)
            start >>= 1
            stop >>= 1
        return self._func(res_left, res_right)

    def __repr__(self):
        return 'SegmentTree({0})'.format(self.data)
p = 998244353

def process(A):
    n = len(A)
    B = []
    for i in range(n):
        B.append([A[i], i])
    B.sort()
    B2 = []
    curr = 0
    data = [-1 for i in range(n + 2)]
    for i in range(n):
        if i > 0 and B[i][0] > B[i - 1][0]:
            curr += 1
        B2.append([curr, B[i][1]])
    Seg = SegmentTree(data=data, default=-1, func=max)
    B2.sort(key=lambda a: a[1])
    S = [None]
    g = [0]
    Sn = 0
    for i in range(n):
        ai = A[i]
        scaled_ai = B2[i][0]
        j = Seg.query(1, scaled_ai + 1)
        gn1 = g[-1]
        if j == -1:
            Sn = ai * (gn1 + (-1) ** i)
        elif j == i - 1:
            Sn = (ai - 1) * S[-1]
        else:
            gn1 = g[-1]
            gi = g[j]
            Sn = ai * (gn1 + (-1) ** (i - j + 1) * gi) + (-1) ** (i - j) * S[j + 1]
        Sn = Sn % p
        Seg[scaled_ai + 1] = i
        S.append(Sn)
        g.append(Sn - gn1)
    print(S[-1])
n = int(input())
A = [int(x) for x in input().split()]
process(A)
(standard_input, packages, output_together) = (1, 1, 1)
(dfs, hashing, read_from_file) = (0, 0, 0)
de = 1
if 1:
    if standard_input:
        import io, os, sys
        input = lambda : sys.stdin.readline().strip()
        import math
        inf = math.inf

        def I():
            return input()

        def II():
            return int(input())

        def MII():
            return map(int, input().split())

        def LI():
            return list(input().split())

        def LII():
            return list(map(int, input().split()))

        def LFI():
            return list(map(float, input().split()))

        def GMI():
            return map(lambda x: int(x) - 1, input().split())

        def LGMI():
            return list(map(lambda x: int(x) - 1, input().split()))
    if packages:
        from io import BytesIO, IOBase
        import random
        import os
        import bisect
        import typing
        from collections import Counter, defaultdict, deque
        from copy import deepcopy
        from functools import cmp_to_key, lru_cache, reduce
        from heapq import merge, heapify, heappop, heappush, heappushpop, nlargest, nsmallest
        from itertools import accumulate, combinations, permutations, count, product
        from operator import add, iand, ior, itemgetter, mul, xor
        from string import ascii_lowercase, ascii_uppercase, ascii_letters
        from typing import *
        BUFSIZE = 4096
    if output_together:

        class FastIO(IOBase):
            newlines = 0

            def __init__(self, file):
                self._fd = file.fileno()
                self.buffer = BytesIO()
                self.writable = 'x' in file.mode or 'r' not in file.mode
                self.write = self.buffer.write if self.writable else None

            def read(self):
                while True:
                    b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
                    if not b:
                        break
                    ptr = self.buffer.tell()
                    (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
                self.newlines = 0
                return self.buffer.read()

            def readline(self):
                while self.newlines == 0:
                    b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
                    self.newlines = b.count(b'\n') + (not b)
                    ptr = self.buffer.tell()
                    (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
                self.newlines -= 1
                return self.buffer.readline()

            def flush(self):
                if self.writable:
                    os.write(self._fd, self.buffer.getvalue())
                    (self.buffer.truncate(0), self.buffer.seek(0))

        class IOWrapper(IOBase):

            def __init__(self, file):
                self.buffer = FastIO(file)
                self.flush = self.buffer.flush
                self.writable = self.buffer.writable
                self.write = lambda s: self.buffer.write(s.encode('ascii'))
                self.read = lambda : self.buffer.read().decode('ascii')
                self.readline = lambda : self.buffer.readline().decode('ascii')
        sys.stdout = IOWrapper(sys.stdout)
    if dfs:
        from types import GeneratorType

        def bootstrap(f, stack=[]):

            def wrappedfunc(*args, **kwargs):
                if stack:
                    return f(*args, **kwargs)
                else:
                    to = f(*args, **kwargs)
                    while True:
                        if type(to) is GeneratorType:
                            stack.append(to)
                            to = next(to)
                        else:
                            stack.pop()
                            if not stack:
                                break
                            to = stack[-1].send(to)
                    return to
            return wrappedfunc
    if hashing:
        RANDOM = random.getrandbits(20)

        class Wrapper(int):

            def __init__(self, x):
                int.__init__(x)

            def __hash__(self):
                return super(Wrapper, self).__hash__() ^ RANDOM
    if read_from_file:
        file = open('input.txt', 'r').readline().strip()[1:-1]
        fin = open(file, 'r')
        input = lambda : fin.readline().strip()
        output_file = open('output.txt', 'w')

        def fprint(*args, **kwargs):
            print(*args, **kwargs, file=output_file)
    if de:

        def debug(*args, **kwargs):
            print('\x1b[92m', end='')
            print(*args, **kwargs)
            print('\x1b[0m', end='')
n = II()
nums = LII()
mod = 998244353
dp0 = [0] * (n + 1)
dp1 = [0] * (n + 1)
acc_dp0 = [0] * (n + 1)
acc_dp1 = [0] * (n + 1)
acc_dp0[0] = 1
stack = [-1]
for i in range(n):
    while stack[-1] != -1 and nums[stack[-1]] >= nums[i]:
        stack.pop()
    p = stack[-1] + 1
    dp0[i + 1] = ((acc_dp1[i] - acc_dp1[p - 1]) * nums[i] + dp0[p]) % mod
    dp1[i + 1] = ((acc_dp0[i] - acc_dp0[p - 1]) * nums[i] + dp1[p]) % mod
    acc_dp0[i + 1] = (acc_dp0[i] + dp0[i + 1]) % mod
    acc_dp1[i + 1] = (acc_dp1[i] + dp1[i + 1]) % mod
    stack.append(i)
print((dp1[-1] - dp0[-1]) * (1 if n % 2 else -1) % mod)
M = 998244353
n = int(input())
a = [int(e) for e in input().split()]
G = [[a[i]] * 19 for i in range(n)]
for p in range(1, 19):
    for i in range(n):
        G[i][p] = min(G[i][p - 1], G[min(n - 1, i + (1 << p - 1))][p - 1])
F = [0] * (n + 1)
F[0] = a[0]
F[-1] = 1
P = [0] * (n + 1)
P[-1] = F[-1]
P[0] = F[0] - P[-1]
for i in range(1, n):
    j = i
    m = a[i]
    for p in range(18, -1, -1):
        j2 = max(0, j - (1 << p))
        m2 = min(m, G[j2][p])
        if m2 == m:
            j = j2
    P2 = P[j - 2] if j - 2 >= -1 else 0
    F[i] = (P[i - 1] - P2 * (-1 if (i - 1 - (j - 2)) % 2 else 1)) * m + (F[j - 1] if j else 0) * (1 if (i - (j - 2)) % 2 else -1)
    F[i] %= M
    P[i] = F[i] - P[i - 1]
    P[i] %= M
print(F[n - 1] % M)