import sys from collections import defaultdict def main(): N, *rest = map(int, sys.stdin.read().split()) A = rest[:N] # Precompute the positions for each x pos = defaultdict(list) for i, a in enumerate(A): pos[a].append(i) total = 0 # For x from 1 to N+1 for x in range(1, N + 2): # Get the positions where x occurs, with sentinels x_pos = [-1] + [i for i, a in enumerate(A) if a == x] + [N] res = 0 # Iterate through intervals between x's occurrences for i in range(1, len(x_pos)): L = x_pos[i-1] + 1 R = x_pos[i] - 1 if L > R: continue # Now, process the interval [L, R] which contains no x k = x - 1 # need to have all 1..k in the subarray if k == 0: # All subarrays in this interval contribute cnt = (R - L + 1) * (R - L + 2) // 2 res += cnt continue # Check if all 1..k are present in the entire array # Precompute for efficiency present = [False] * (k + 1) for a in A: if 1 <= a <= k: present[a] = True if not all(present[1:]): continue # no subarrays can contribute # Now, compute the number of subarrays in [L, R] that contain all 1..k # Using sliding window freq = defaultdict(int) current = 0 left = L cnt = 0 for right in range(L, R + 1): a = A[right] if 1 <= a <= k: if freq[a] == 0: current += 1 freq[a] += 1 # Shrink the window as much as possible while current == k and left <= right: a_left = A[left] if 1 <= a_left <= k: freq[a_left] -= 1 if freq[a_left] == 0: current -= 1 left += 1 # The number of valid subarrays ending at right is left - L cnt += left - L res += cnt total += x * res print(total) if __name__ == '__main__': main()