Problem:
 Score : 400 points    Problem Statement Mountaineers Mr. Takahashi and Mr. Aoki recently trekked across a certain famous mountain range.
The mountain range consists of N mountains, extending from west to east in a straight line as Mt. 1 , Mt. 2 , ..., Mt. N .
Mr. Takahashi traversed the range from the west and Mr. Aoki from the east.  The height of Mt. i is h_i , but they have forgotten the value of each h_i .
Instead, for each i ( 1 ≤ i ≤ N ), they recorded the maximum height of the mountains climbed up to the time they reached the peak of Mt. i (including Mt. i ).
Mr. Takahashi's record is T_i and Mr. Aoki's record is A_i .  We know that the height of each mountain h_i is a positive integer.
Compute the number of the possible sequences of the mountains' heights, modulo 10^9 + 7 .  Note that the records may be incorrect and thus there may be no possible sequence of the mountains' heights.
In such a case, output 0 .      Constraints  1 ≤ N ≤ 10^5  1 ≤ T_i ≤ 10^9  1 ≤ A_i ≤ 10^9  T_i ≤ T_{i+1} ( 1 ≤ i ≤ N - 1 )  A_i ≥ A_{i+1} ( 1 ≤ i ≤ N - 1 )         Input The input is given from Standard Input in the following format:  N  T_1  T_2  ...  T_N  A_1  A_2  ...  A_N       Output Print the number of possible sequences of the mountains' heights, modulo 10^9 + 7 .        Sample Input 1 5
1 3 3 3 3
3 3 2 2 2      Sample Output 1 4  The possible sequences of the mountains' heights are:   1, 3, 2, 2, 2   1, 3, 2, 1, 2   1, 3, 1, 2, 2   1, 3, 1, 1, 2    for a total of four sequences.       Sample Input 2 5
1 1 1 2 2
3 2 1 1 1      Sample Output 2 0  The records are contradictory, since Mr. Takahashi recorded 2 as the highest peak after climbing all the mountains but Mr. Aoki recorded 3 .       Sample Input 3 10
1 3776 3776 8848 8848 8848 8848 8848 8848 8848
8848 8848 8848 8848 8848 8848 8848 8848 3776 5      Sample Output 3 884111967  Don't forget to compute the number modulo 10^9 + 7 .       Sample Input 4 1
17
17      Sample Output 4 1  Some mountain ranges consist of only one mountain.

Solution (Python):
def examA():
    N = I()
    T = LI()
    A = LI()
    S = [-1]*N
    S[0] = T[0]; S[-1]=A[-1]
    ans = 1
    for i in range(1,N):
        if T[i]==T[i-1]:
            continue
        S[i] = T[i]
    flag = -1
    for i in range(N):
        if S[i]==A[i]:
            flag = i
            break
    if not (A[flag]==A[0] and A[flag]==T[-1]):
        print(0)
        return
    for i in range(N-1)[::-1]:
        if A[i]==A[i+1]:
            continue
        if S[i]==-1:
            S[i] = A[i]
        else:
            S[i] = max(S[i],A[i])
    
    P = []
    pindex = []
    for i in range(N):
        if S[i]==-1:
            continue
        P.append(S[i])
        pindex.append(i)
    flag_U = True
    for i in range(len(P)-1):
        if P[i+1]>P[i]:
            if not flag_U:
                print(0)
                return
        elif P[i+1]<P[i]:
            flag_U = False
    ans = 1
    p = -1
    for i in range(N):
        if S[i]==-1:
            cur = min(P[p + 1], P[p])
            ans *= cur
            ans %= mod
        else:
            p += 1

    print(ans)
    return

def examB():
    ans = 0
    print(ans)
    return

def examC():
    ans = 0
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

import sys,copy,bisect,itertools,heapq,math,random
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

if __name__ == '__main__':
    examA()

"""

"""

Solution (Python):
N = int(input())
T = list(map(int, input().split()))
A = list(map(int, input().split()))

H = [[-1, 10**9] for i in range(N)]

prev = 0
for i, x in enumerate(T):
    if prev != x:
        if H[i][0] < 0:
            H[i][0] = x
        elif H[i][0] != x:
            print(0)
            exit(0)
    prev = x
    H[i][1] = min(H[i][1], x)
prev = 0
for i in range(N-1, -1, -1):
    x = A[i]
    if prev != x:
        if H[i][0] < 0:
            if H[i][1] >= x:
                H[i][0] = x
            else:
                print(0)
                exit(0)
        elif H[i][0] != x:
            print(0)
            exit(0)
    prev = x
    H[i][1] = min(H[i][1], x)
ans = 1
mod = 10**9 + 7
for x, y in H:
    if x > 0:
        continue
    else:
        ans *= y
        ans %= mod
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
N = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
mod = 10 ** 9 + 7
t = [10 ** 10 for _ in range(N)]
t[0] = a[0]
t[-1] = b[-1]
s = set()
s.add(0)
s.add(N - 1)
if a[0] > b[0] or (a[-1] < b[-1]):
  print(0)
  exit(0)
if a[-1] != b[0]:
  print(0)
  exit(0)
for i in range(N - 1):
  if a[i + 1] > a[i]:
    if t[i + 1] > 0 and (t[i + 1] in range(a[i + 1])):
      print(0)
      exit(0)
    s.add(i + 1)
    t[i + 1] = a[i + 1]
  else: t[i + 1] = min(t[i + 1], t[i])

for i in range(N - 1, 0, -1):
  if b[i - 1] > b[i]:
    if t[i - 1] > 0 and (t[i - 1] in range(b[i - 1])):
      print(0)
      exit(0)
    s.add(i - 1)
    t[i - 1] = b[i - 1]
  else: t[i - 1] = min(t[i - 1], t[i])

res = 1
for i in range(N):
  if i in s: continue
  res *= t[i]
  res %= mod
print(res)

Solution (Python):
N = int(input())
T = list(map(int, input().split()))
A = list(map(int, input().split()))

class Mint:
    @staticmethod
    def get_value(x): return x.value if isinstance(x, Mint) else x

    def __init__(self, val, mod=10**9+7):
        val = Mint.get_value(val)
        self.__mod = mod
        self.__val = val % self.__mod

    @property
    def value(self): return self.__val
    @property
    def inverse(self): return pow(self.__val, self.__mod - 2, self.__mod)

    def __eq__(self, other): return self.__val == other.val
    def __ne__(self, other): return self.__val != other.val

    def __neg__(self): return Mint(self.__val, self.__mod)

    def __iadd__(self, other):
        other = Mint.get_value(other)
        self.__val = (self.__val + other) % self.__mod
        return self
    def __add__(self, other):
        new = Mint(self.__value, self.__mod)
        new += other
        return new
    def __radd__(self, other): return self + other

    def __isub__(self, other):
        other = Mint.get_value(other)
        self.__val = (self.__val - other + self.__mod) % self.__mod
        return self
    def __sub__(self, other):
        new = Mint(self.__value, self.__mod)
        new -= other
        return new
    def __rsub__(self, other):
        new = Mint(Mint.get_value(other), self.__mod)
        new -= self
        return new

    def __imul__(self, other):
        other = Mint.get_value(other)
        self.__val = self.__val * other % self.__mod
        return self
    def __mul__(self, other):
        new = Mint(self.__value, self.__mod)
        new *= other
        return new
    def __rmul__(self, other): return self * other

    def __ifloordiv__(self, other):
        other = Mint(other, self.__mod)
        self *= other.inverse
        return self
    def __floordiv__(self, other):
        new = Mint(self.__value, self.__mod)
        new //= other
        return new
    def __rfloordiv__(self, other):
        new = Mint(Mint.get_value(other), self.__mod)
        new //= self
        return new

if T[N-1] != A[0]:
    print(0)
    exit()

ans = Mint(1)
for i in range(N):
    if i==0 or i==N-1: continue
    if T[i-1] != T[i]:
        if T[i] == A[0] and A[i] != A[0]:
            print(0)
            exit()
        continue
    if A[i] != A[i+1]:
        if A[i] == A[0] and T[i] != A[0]:
            print(0)
            exit()
        continue
    ans *= min(T[i], A[i])
print(ans.value)

Solution (Python):
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))



N = I()
T = LI()
A = LI()

if T[0] > A[0]:
    print(0)
    exit()

if T[N-1] < A[N-1]:
    print(0)
    exit()

ans = 1
for i in range(1,N-1):
    if T[i-1] != T[i]:
        if A[i] < T[i]:
            print(0)
            exit()
        else:
            continue
    else:
        if A[i+1] != A[i]:
            if T[i] < A[i]:
                print(0)
                exit()
            else:
                continue
        else:
            ans *= min(A[i],T[i])
            ans %= mod

print(ans)

Solution (Python):
MOD=10**9+7
class Fp(int):
    def __new__(self,x=0):return super().__new__(self,x%MOD)
    def inv(self):return self.__class__(super().__pow__(MOD-2,MOD))
    def __add__(self,value):return self.__class__(super().__add__(value))
    def __sub__(self,value):return self.__class__(super().__sub__(value))
    def __mul__(self,value):return self.__class__(super().__mul__(value))
    def __floordiv__(self,value):return self.__class__(self*self.__class__(value).inv())
    def __pow__(self,value):return self.__class__(super().__pow__(value%(MOD-1), MOD))
    __radd__=__add__
    __rmul__=__mul__
    def __rsub__(self,value):return self.__class__(-super().__sub__(value))
    def __rfloordiv__(self,value):return self.__class__(self.inv()*value)
    def __iadd__(self,value):self=self+value;return self
    def __isub__(self,value):self=self-value;return self
    def __imul__(self,value):self=self*value;return self
    def __ifloordiv__(self,value):self=self //value;return self
    def __ipow__(self,value):self=self**value;return self
    def __neg__(self):return self.__class__(super().__neg__())

N=int(input())
T=list(map(int, input().split()))+[0]
A=list(map(int, input().split()))+[0]
ans=Fp(1)
for i in range(N):
    if T[i-1]<T[i] and A[i]>A[i+1]:
        ans*=T[i]==A[i]
    elif T[i-1]<T[i]:
        ans*=T[i]<=A[i]
    elif A[i]>A[i+1]:
        ans*=A[i]<=T[i]
    else:
        ans*=min(T[i],A[i])
print(ans)

Solution (Python):
import numpy as np
from itertools import groupby

N = int(input())
T = np.array(['0'] + input().split() + ['10000000000'], np.int64)
A = np.array(['10000000000'] + input().split() + ['0'], np.int64)
mod = 10 ** 9 + 7

t = (T[1:] != T[:-1]) * T[1:]
a = (A[1:] != A[:-1]) * A[:-1]
t = t[:-1]
a = a[1:]

flag = True
idx = np.where((t != 0) & (a != 0))[0]
if np.any(t[idx] != a[idx]):
    flag = False

seq = np.maximum(t, a)
if np.any(seq > T[1:-1]) or np.any(seq > A[1:-1]):
    flag = False

if flag:
    group = [(i, len(list(j))) for i, j in groupby(seq.tolist())]
    answer = 1
    for i, (key, n) in enumerate(group):
        if key == 0:
            answer *= pow(min(group[i - 1][0], group[i + 1][0]), n, mod)
            answer %= mod
    print(answer)
else:
    print(0)

Solution (Python):
import numpy as np
from itertools import groupby

N = int(input())
T = np.array(['0'] + input().split() + ['10000000000'], np.int64)
A = np.array(['10000000000'] + input().split() + ['0'], np.int64)
mod = 10 ** 9 + 7

t = (T[1:] != T[:-1]) * T[1:]
a = (A[1:] != A[:-1]) * A[:-1]
t = t[:-1]
a = a[1:]
seq = np.zeros(N, np.int64)

flag = True
tmp = np.where((t != 0) & (a != 0))[0]
if np.any(t[tmp] != a[tmp]):
    flag = False
seq = np.maximum(t, a)
if np.any(seq > T[1:-1]) or np.any(seq > A[1:-1]):
    flag = False

if flag:
    group = [(i, len(list(j))) for i, j in groupby(seq.tolist())]
    answer = 1
    for i in range(len(group)):
        if group[i][0] == 0:
            answer *= pow(min(group[i - 1][0], group[i + 1][0]), group[i][1], mod)
            answer %= mod
    print(answer)
else:
    print(0)

Solution (Python):
n = int(input())
t = list(map(int, input().split()))
a = list(map(int, input().split()))
mt_t=[0]*n
mt_a=[0]*n
last=0
for i in range(len(t)):
    if last < t[i]:
        mt_t[i] = -t[i]
        last=t[i]
    else:
        mt_t[i] = last
last=0
for i in reversed(range(len(t))):
    if last < a[i]:
        mt_a[i] = -a[i]
        last=a[i]
    else:
        mt_a[i] = last
mts = [0]*n
for i in range(len(t)):
    if mt_t[i] < 0 and mt_a[i] < 0:
        if mt_t[i] != mt_a[i]:
            print(0)
            exit()
    elif mt_t[i] < 0 or mt_a[i] < 0:
        kaku =abs(min(mt_t[i],mt_a[i]))
        kouho=max(mt_t[i],mt_a[i])
        if kouho < kaku:
            print(0)
            exit()
    mts[i] = min(mt_t[i],mt_a[i])

ans=1
for num in mts:
    if num > 0:
        ans*=num
        ans%=(10**9+7)
print(ans)

Solution (Python):
N = int(input())
T = [int(t) for t in input().split()]
A = [int(a) for a in input().split()]

mod = 10**9+7
TM = [0]*N
TM[0] = T[0]
AM = [0]*N
AM[-1] = A[-1]
for i in range(N-1):
    if T[i] < T[i+1]:
        TM[i+1] = T[i+1]
    if A[i+1] < A[i]:
        AM[i] = A[i]

M = [0]*N
ans = 1
for i in range(N):
    if TM[i] > 0 and AM[i] > 0 and TM[i] != AM[i]:
        ans = 0
    elif TM[i] > 0 and AM[i] == 0 and TM[i] <= A[i]:
        M[i] = TM[i]
    elif TM[i] == 0 and AM[i] > 0 and AM[i] <= T[i]:
        M[i] = AM[i]
    elif TM[i] == AM[i]:
        M[i] = TM[i]
    elif TM[i] == 0 and AM[i] == 0:
        continue
    else:
        ans = 0
        break

for i in range(N):
    if M[i] > 0:
        continue
    ans *= min(T[i], A[i])
    ans %= mod

print(ans)

Solution (Python):
n = int(input())
t = list(map(int, input().split()))
a = list(map(int, input().split()))
mod = 10**9+7
ans = 1
if n == 1 and t != a:
    print(0)
    exit()
for i in range(1,n-1):
    if t[i-1] == t[i] and a[i] == a[i+1]:
        ans = (ans*min(t[i],a[i]))%mod
    elif t[i-1] < t[i] and t[i] > a[i]:
        print(0)
        exit()
    elif a[i] > a[i+1] and t[i] < a[i]:
        print(0)
        exit()
print(ans)

Solution (Python):
N = int(input())
A = list(map(int, input().split()))
T = list(map(int, input().split()))

mod = int(1e9+7)

dp = [0] * (N)
dp[0] = 1


Amax = max(A)
Aleft, Tright = -1, -1
Tmax = max(T)
for i in range(N):
  if Amax == A[i]:
    Aleft = i
    break
for i in range(N-1,-1,-1):
  if Tmax == T[i]:
    Tright = i
    break
if Aleft > Tright:
  print(0)
  exit(0)
if A[-1] != T[0]:
  print(0)
  exit(0)
  
for i in range(1,N-1):
  if A[i-1] < A[i] or T[i] > T[i+1]:
    dp[i] = dp[i-1]
  else:
    dp[i] = dp[i-1] * min(A[i], T[i]) % mod
  
print(dp[N-2])

Solution (Python):

N = int(input())
A = tuple(map(int, input().split()))
B = tuple(map(int, input().split()))
mod = 10**9+7
 

fix_a= [0]*(N)
fix_b= [0]*(N)
fix_a[0] = A[0]
fix_b[-1] = B[-1]
for i in range(N-1):
    if A[i+1]>A[i]:
        fix_a[i+1] = A[i+1]
    if B[-(i+2)]>B[-(i+1)]:
        fix_b[-(i+2)] = B[-(i+2)]

ans = 1
for i in range(N):
    if fix_a[i]:
        if B[i]<fix_a[i]:
            ans = 0
            break
    if fix_b[i]:
        if A[i]<fix_b[i]:
            ans = 0
            break
            
for i in range(N):
    if fix_a[i] or fix_b[i]:
        continue
    ans *= min(A[i], B[i])
    ans %= mod
    
if A[-1] != B[0]:
    ans = 0
    
print(ans)

Solution (Python):
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
c = []
for i in range(n):
  c.append(min(a[i],b[i]))
d = [0 for _ in range(n)]
e = [0 for _ in range(n)]
d[0] = 1
e[-1] = 1
for i in range(1,n):
  if a[i-1] != a[i]:
    d[i] = 1
for i in range(n-1)[::-1]:
  if b[i+1] != b[i]:
    e[i] = 1
for i in range(n):
  if d[i] * e[i] == 1 and a[i] != b[i]:
    print(0)
    break
else:
  for i in range(n):
    if d[i] == 1 and a[i] != c[i]:
      print(0)
      break
    if e[i] == 1 and b[i] != c[i]:
      print(0)
      break
  else:
    ans = 1
    mod = 10 ** 9 + 7
    for i in range(n):
      if d[i] == e[i] == 0:
        ans *= c[i]
        ans %= mod
    print(ans)

Solution (Python):
from sys import stdout
printn = lambda x: stdout.write(str(x))
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True 
BIG = 999999999
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

n = inn()
t = inl()
a = inl()
mx = max(t)
if max(a) != mx:
    print(0)
    exit()
for p in range(n):
    if t[p]==mx:
        break
for q in range(n-1,-1,-1):
    if a[q]==mx:
        break
if q<p:
    print(0)
    exit()
prod = 1
prev = -1
for i in range(p):
    if t[i]==prev:
        prod = (prod*prev)%R
    else:
        prev = t[i]
prev = -1
for i in range(n-1,q,-1):
    if a[i]==prev:
        prod = (prod*prev)%R
    else:
        prev = a[i]
print((prod*(mx**max(0,q-p-1)))%R)

Solution (Python):

import sys
import numpy as np
sys.setrecursionlimit(10 ** 7)

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N = ir()
T = np.array(lr()).astype('int64')
A = np.array(lr()).astype('int64')
MOD = 10 ** 9 + 7

T_low = T.copy()
T_low[1:][T[1:] <= T[:-1]] = 1
A_low = A.copy()
A_low[:-1][A[:-1] <= A[1:]] = 1

lower = np.maximum(T_low, A_low)
upper = np.minimum(T, A)
domain = np.maximum(0, upper - lower + 1) 
L = len(domain); LSQ = int(L**.5 + 1) 
domain = np.resize(domain, LSQ**2) 
domain[L:] = 1 
domain = domain.reshape((LSQ, LSQ))
for n in range(1, LSQ):
    domain[:, n] *= domain[:, n-1]; domain[:, n] %= MOD
for n in range(1, LSQ):
    domain[n, -1] *= domain[n-1, -1]; domain[n] %= MOD
answer = domain[-1, -1]
print(answer)

Solution (Python):
MOD = 10**9+7
n = int(input())
T = list(map(int, input().split()))
A = list(map(int, input().split()))
C = [0]*n
if T[0] > A[0] or T[-1] < A[-1]:
  print(0)
  exit()
C[0], C[-1] = 1, 1
for i in range(1, n-1):
  if T[i-1] == T[i]:
    t = -T[i]
  else:
    t = T[i]
  if A[i] == A[i+1]:
    a = -A[i]
  else:
    a = A[i]
  if t > 0 and a > 0:
    if t != a:
      print(0)
      exit()
    C[i] = 1
  else:
    if t > 0:
      if t > abs(a):
        print(0)
        exit()
      C[i] = 1
    elif a > 0:
      if a > abs(t):
        print(0)
        exit()
      C[i] = 1
    else:
      C[i] = min(-t, -a)
ans = 1
for i in C:
  ans *= i
  ans %= MOD
print(ans)

Solution (Python):
import sys, bisect, math, itertools, string, queue, copy


from collections import Counter,defaultdict,deque
from itertools import permutations, combinations
from heapq import heappop, heappush
input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(input()) 
def inpm(): return map(int,input().split()) 
def inpl(): return list(map(int, input().split())) 
def inpls(): return list(input().split())  
def inplm(n): return list(int(input()) for _ in range(n)) 
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)] 
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)]) 

 
def main():
    n = inp()
    t = inpl()
    a = inpl()
    m = [0 for _ in range(n)]
    m[0] = t[0]
    for i in range(1,n):
        if t[i]>t[i-1]:
            m[i] = t[i]
    m[n-1] = a[n-1]
    for i in range(n-2,-1,-1):
        if a[i]>a[i+1]:
            m[i] = a[i]
    ans = 1
    mt,ma = 0,0
    for i in range(n):
        mt = max(mt,m[i])
        ma = max(ma,m[n-1-i])
        if mt != t[i] or ma != a[n-1-i]:
            print(0)
            return
    for i in range(n):
        if m[i] == 0:
            ans = (ans*min(t[i],a[i]))%mod
    print(ans)
    
if __name__ == "__main__":
    main()

Solution (Python):











import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,sqrt,factorial,hypot,log 
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint
def ceil(a,b): return (a+b-1)//b
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')

class ModInt:
    def __init__(self, x):
        self.x = x % mod
    
    def __str__(self):
        return str(self.x)
    
    __repr__ = __str__

    def __add__(self, other):
        if isinstance(other, ModInt):
            return ModInt(self.x + other.x)
        else:
            return ModInt(self.x + other)

    __radd__ = __add__
        
    def __sub__(self, other):
        if isinstance(other, ModInt):
            return ModInt(self.x - other.x)
        else:
            return ModInt(self.x - other)

    def __rsub__(self, other):
        if isinstance(other, ModInt):
            return ModInt(other.x - self.x)
        else:
            return ModInt(other - self.x)

    def __mul__(self, other):
        if isinstance(other, ModInt):
            return ModInt(self.x * other.x)
        else:
            return ModInt(self.x * other)

    __rmul__ = __mul__

    def __truediv__(self, other):
        if isinstance(other, ModInt):
            return ModInt(self.x * pow(other.x, mod-2,mod))
        else:
            return ModInt(self.x * pow(other, mod - 2, mod))
            
    def __rtruediv(self, other):
        if isinstance(other, self):
            return ModInt(other * pow(self.x, mod - 2, mod))
        else:
            return ModInt(other.x * pow(self.x, mod - 2, mod))
            

    def __pow__(self, other):
        if isinstance(other, ModInt):
            return ModInt(pow(self.x, other.x, mod))
        else:
            return ModInt(pow(self.x, other, mod))
            

    def __rpow__(self, other):
        if isinstance(other, ModInt):
            return ModInt(pow(other.x, self.x, mod))
        else:
            return ModInt(pow(other, self.x, mod))

def main():
    N = I()
    T = LI()
    A = LI()

    lim = [inf]*N
    confirm = [None]*N
    
    now = 0
    for i,a in enumerate(T):
        if now < a:
            confirm[i] = a
            now = a
        lim[i] = a
    
    now = 0
    for i in range(N)[::-1]:
        a = A[i]
        if now < a:
            if confirm[i] is not None:
                if confirm[i] != a:
                    print(0)
                    return
            if lim[i] < a:
                print(0)
                return
            confirm[i] = a
            now = a
        lim[i] = min(lim[i], a)
        if confirm[i] is not None:
            if confirm[i] > lim[i]:
                print(0)
                return 
    
    ans = ModInt(1)
    for i,(l,c) in enumerate(zip(lim, confirm)):
        if c is None:
            ans *= l

    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
N = int(input())
T = list(map(int, input().split()))
A = list(map(int, input().split()))

M = [[-1, 10**9] for i in range(N)]

for i in range(N):
    if i == 0:
        M[i][0] = T[i]
    else:
        if T[i] != T[i-1]:
            M[i][0] = T[i]
        else:
            M[i][1] = T[i]

for i in range(N-1, -1, -1):
    if i == N-1:
        if M[i][0] != -1 and M[i][0] != A[i]:
            print(0)
            exit(0)
        else:
            if M[i][1] >= A[i]:
                M[i][0] = A[i]
            else:
                print(0)
                exit(0)

    else:
        if A[i] != A[i+1]:
            if M[i][0] != -1 and M[i][0] != A[i]:
                print(0)
                exit(0)
            else:
                if A[i] <= M[i][1]:
                    M[i][0] = A[i]
                else:
                    print(0)
                    exit(0)
        else:
            M[i][1] = min(M[i][1], A[i])
ans = 1
mod = (10 ** 9) + 7
for x, y in M:
    if x == -1:
        ans *= y
        ans %= mod

print(ans)

Solution (Python):
import sys
import numpy as np
sys.setrecursionlimit(10 ** 7)

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N = ir()
T = np.array(lr()).astype('int64')
A = np.array(lr()).astype('int64')
MOD = 10 ** 9 + 7

T_low = T.copy()
T_low[1:][T[1:] <= T[:-1]] = 1
A_low = A.copy()
A_low[:-1][A[:-1] <= A[1:]] = 1

lower = np.maximum(T_low, A_low)
upper = np.minimum(T, A)
domain = np.maximum(0, upper - lower + 1) 
L = len(domain); LSQ = int(L**.5 + 1) 
domain = np.resize(domain, LSQ**2) 
domain[L:] = 1 
domain = domain.reshape((LSQ, LSQ))
for n in range(1, LSQ):
    domain[:, n] *= domain[:, n-1]; domain[:, n] %= MOD
for n in range(1, LSQ):
    domain[n] *= domain[n-1, -1]; domain[n] %= MOD
answer = domain[-1, -1]
print(answer)

Solution (Python):
import sys
import numpy as np
sys.setrecursionlimit(10 ** 7)

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N = ir()
T = np.array(lr()).astype('int64')
A = np.array(lr()).astype('int64')
MOD = 10 ** 9 + 7

T_low = T.copy()
T_low[1:][T[1:] <= T[:-1]] = 1
A_low = A.copy()
A_low[:-1][A[:-1] <= A[1:]] = 1

lower = np.maximum(T_low, A_low)
upper = np.minimum(T, A)
domain = np.maximum(0, upper - lower + 1) 
L = len(domain); LSQ = int(L**.5 + 1)
domain = np.resize(domain, LSQ**2) 
domain[L:] = 1 
domain = domain.reshape((LSQ, LSQ))
for n in range(1, LSQ):
    domain[:, n] *= domain[:, n-1]; domain[:, n] %= MOD
for n in range(1, LSQ):
    domain[n] *= domain[n-1, -1]; domain[n] %= MOD
answer = domain[-1, -1]
print(answer)

Solution (Python):

N = int(input())
A = tuple(map(int, input().split()))
B = tuple(map(int, input().split()))
mod = 10**9+7
 

fix_a= [0]*(N)
fix_b= [0]*(N)
fix_a[0] = A[0]
fix_b[-1] = B[-1]
for i in range(N-1):
    if A[i+1]>A[i]:
        fix_a[i+1] = A[i+1]
    if B[-(i+2)]>B[-(i+1)]:
        fix_b[-(i+2)] = B[-(i+2)]

ans = 1
for i in range(N):
    if fix_a[i]:
        if B[i]<fix_a[i]:
            ans = 0
            break
    if fix_b[i]:
        if A[i]<fix_b[i]:
            ans = 0
            break
            
for i in range(N):
    if fix_a[i] or fix_b[i]:
        continue
    ans *= min(A[i], B[i])
    ans %= mod
    
if A[-1] != B[0]:
    ans = 0
    
print(ans)

Solution (Python):

if __name__ == '__main__':
    N = int(input())
    T = list(map(int, input().split()))
    A = list(map(int, input().split()))
    ans = 1
    if T[0] > A[0] or T[N-1] < A[N-1]:
        ans = 0
    for i in range(N-1):
        if T[i] > T[i+1]:
            ans = 0
        if T[i] < T[i+1] and T[i+1] > A[i+1]:
            ans = 0
    for i in range(N-1, 0, -1):
        if A[i] > A[i-1]:
            ans = 0
        if A[i] < A[i-1] and A[i-1] > T[i-1]:
            ans = 0
    for i in range(1, N-1):
        if T[i] != T[i-1] or A[i] != A[i+1]:
            continue
        else:
            ans *= min(A[i], T[i])
            ans %= int(1e9+7)
    print(ans)

Solution (Python):
def main():
    mod = 10 ** 9 + 7

    n = int(input())
    *t, = map(int, input().split())
    *a, = map(int, input().split())

    if t[-1] != a[0]:
        
        print(0)
        return

    ret = 1

    
    for i in range(n):
        if i == 0:
            lo = hi = t[i]
        else:
            if t[i - 1] < t[i]:
                
                lo = hi = t[i]
            elif t[i - 1] == t[i]:
                
                lo = 1
                hi = t[i]
            else:
                
                print(0)
                return

        if i == n - 1:
            lo = max(lo, a[i])
            hi = min(hi, a[i])
        else:
            if a[i] > a[i + 1]:
                
                lo = max(lo, a[i])
                hi = min(hi, a[i])
            elif a[i] == a[i + 1]:
                
                lo = max(lo, 1)
                hi = min(hi, a[i])
            else:
                
                print(0)
                return

        if lo > hi:
            print(0)
            return

        ret = ret * (hi - lo + 1) % mod

    print(ret)


if __name__ == '__main__':
    main()

Solution (Python):
import sys
input = sys.stdin.readline
n = int(input())
T = list(map(int,input().split()))
A = list(map(int,input().split()))

B = [[-1] * n for i in range(4)]

B[0][0] = T[0]
B[1][0] = T[0]+1

for i in range(1, n):
    if T[i] == T[i-1]:
        B[0][i] = 1
        B[1][i] = T[i] + 1
    elif T[i] > T[i-1]:
        B[0][i] = T[i]
        B[1][i] = T[i] + 1

B[2][n-1] = A[-1]
B[3][n-1] = A[-1]+1

for i in range(n-2, -1, -1):
    if A[i] == A[i+1]:
        B[2][i] = 1
        B[3][i] = A[i] + 1
    elif A[i] > A[i+1]:
        B[2][i] = A[i]
        B[3][i] = A[i] + 1



ans = 1
mod = 10**9+7
for i in range(n):
    ans = (ans * max(0, min(B[1][i], B[3][i]) - max(B[0][i], B[2][i]))) % mod
print(ans)

Solution (Python):
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations,groupby
import sys
import bisect
import string
import math
import time
import random
def S_():
    return input()
def LS():
    return [i for i in input().split()]
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def LtoS(ls):
    return ''.join([chr(i+97) for i in ls])
def GI(V,E,Directed=False,index=0):
    org_inp=[]
    g=[[] for i in range(n)]
    for i in range(E):
        inp=LI()
        org_inp.append(inp)
        if index==0:
            inp[0]-=1
            inp[1]-=1
        if len(inp)==2:
            a,b=inp
            g[a].append(b)
            if not Directed:
                g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp
            aa=(inp[0],inp[2])
            bb=(inp[1],inp[2])
            g[a].append(bb)
            if not Directed:
                g[b].append(aa)
    return g,org_inp
def bit_combination(k,n=2):
    rt=[]
    for tb in range(n**k):
        s=[tb//(n**bt)%n for bt in range(k)]
        rt+=[s]
    return rt
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()

input=lambda: sys.stdin.readline().rstrip()

def ran_input():
    import random
    n=random.randint(4,16)
    rmin,rmax=1,10
    a=[random.randint(rmin,rmax) for _ in range(n)]
    return n,a

show_flg=False
show_flg=True

ans=0

n=I()
L=LI()
R=LI()
h=[() for i in range(n)]

p=0

for i in range(n):
    c=L[i]
    if c>p:
        h[i]=(c,c)
    else:
        h[i]=(1,c)
    p=c

p=0
for i in range(n-1,-1,-1):
    c=R[i]
    l,r=h[i]
    if c>p:
        if l==r:
            if l!=c:
                h[i]=(c,c-1)
        elif l<=c<=r:
            h[i]=(c,c)
        else:
            h[i]=(c,c-1)
    else:
        h[i]=(max(l,1),min(r,c))
    p=c

ans=1
for i in range(n):
    l,r=h[i]
    ans*=r-l+1
    ans%=mo

print(ans)