The only difference between easy and hard versions is constraints.

Ivan plays a computer game that contains some microtransactions to make characters look cooler. Since Ivan wants his character to be really cool, he wants to use some of these microtransactions — and he won't start playing until he gets all of them.

Each day (during the morning) Ivan earns exactly one burle.

There are $n$ types of microtransactions in the game. Each microtransaction costs $2$ burles usually and $1$ burle if it is on sale. Ivan has to order exactly $k_i$ microtransactions of the $i$-th type (he orders microtransactions during the evening).

Ivan can order any (possibly zero) number of microtransactions of any types during any day (of course, if he has enough money to do it). If the microtransaction he wants to order is on sale then he can buy it for $1$ burle and otherwise he can buy it for $2$ burles.

There are also $m$ special offers in the game shop. The $j$-th offer $(d_j, t_j)$ means that microtransactions of the $t_j$-th type are on sale during the $d_j$-th day.

Ivan wants to order all microtransactions as soon as possible. Your task is to calculate the minimum day when he can buy all microtransactions he want and actually start playing.


-----Input-----

The first line of the input contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5$) — the number of types of microtransactions and the number of special offers in the game shop.

The second line of the input contains $n$ integers $k_1, k_2, \dots, k_n$ ($0 \le k_i \le 2 \cdot 10^5$), where $k_i$ is the number of copies of microtransaction of the $i$-th type Ivan has to order. It is guaranteed that sum of all $k_i$ is not less than $1$ and not greater than $2 \cdot 10^5$.

The next $m$ lines contain special offers. The $j$-th of these lines contains the $j$-th special offer. It is given as a pair of integers $(d_j, t_j)$ ($1 \le d_j \le 2 \cdot 10^5, 1 \le t_j \le n$) and means that microtransactions of the $t_j$-th type are on sale during the $d_j$-th day.


-----Output-----

Print one integer — the minimum day when Ivan can order all microtransactions he wants and actually start playing.


-----Examples-----
Input
5 6
1 2 0 2 0
2 4
3 3
1 5
1 2
1 5
2 3

Output
8

Input
5 3
4 2 1 3 2
3 5
4 2
2 5

Output
20

Difficulty: HARD

Solutions:
import sys

def main():
	(n, m) = map(int, input().split())
	k = [int(x) for x in input().split()]
	d = [[] for _ in range(4 * 10 ** 5 + 1)]
	for j in range(m):
		(dj, tj) = map(int, input().split())
		d[dj - 1].append(tj - 1)
	(lo, hi) = (0, 4 * 10 ** 5 + 1)
	while lo < hi:
		mi = (hi + lo) // 2
		cash = mi
		offset = 0
		_k = k[:]
		for i in reversed(range(mi)):
			for j in d[i]:
				while cash and _k[j]:
					_k[j] -= 1
					cash -= 1
			if cash == i + 1:
				cash -= 2
				offset += 1
		if 2 * (sum(_k) - offset) <= cash:
			hi = mi
		else:
			lo = mi + 1
	print(lo)
input = iter(sys.stdin.read().splitlines()).__next__
main()


import sys
from array import array
from typing import List, Tuple, TypeVar, Generic, Sequence, Union

def input():
	return sys.stdin.buffer.readline().decode('utf-8')

def main():
	(n, m) = map(int, input().split())
	k = array('i', [0] + list(map(int, input().split())))
	sale = sorted((tuple(map(int, input().split())) for _ in range(m)), reverse=True)
	total = sum(k)
	visited = array('b', [0]) * (n + 1)
	(ok, ng) = (total * 2 + 1, total - 1)
	while abs(ok - ng) > 1:
		mid = ok + ng >> 1
		for i in range(1, n + 1):
			visited[i] = 0
		(bought, money) = (0, mid)
		for (di, ti) in sale:
			if di > mid or visited[ti]:
				continue
			visited[ti] = 1
			if money > di:
				money = di
			x = k[ti] if k[ti] <= money else money
			bought += x
			money -= x
		if 2 * total - bought <= mid:
			ok = mid
		else:
			ng = mid
	print(ok)
main()


def check(x):
	last = [0] * (n + 1)
	for i in tmp:
		if i[0] > x:
			break
		else:
			last[i[1]] = i[0]
	sal = [0] * (x + 1)
	for i in range(1, n + 1):
		sal[last[i]] += lis[i - 1]
	c = 0
	for i in range(1, x + 1):
		c += 1
		if sal[i] >= c:
			sal[i] -= c
			c = 0
		else:
			c -= sal[i]
			sal[i] = 0
	if sum(sal) * 2 <= c:
		return True
	else:
		return False
(n, m) = map(int, input().split())
lis = list(map(int, input().split()))
tmp = []
for _ in range(m):
	(a, b) = map(int, input().split())
	tmp.append([a, b])
tmp.sort()
l = 0
r = sum(lis) * 2
while l <= r:
	mid = l + (r - l) // 2
	if check(mid):
		r = mid - 1
	else:
		l = mid + 1
if check(r):
	print(r)
elif check(l):
	print(l)
else:
	print(l + 1)


import math
from collections import defaultdict
import sys

def main():
	(n, m) = map(int, input().split())
	k = list(map(int, input().split()))
	sales = [(0, 0)] * m
	for i in range(m):
		(a, b) = map(int, input().split())
		sales[i] = (b, a)

	def check(days):
		last_sale = {}
		for sale in sales:
			if sale[1] <= days:
				if sale[0] not in last_sale or sale[1] > last_sale[sale[0]]:
					last_sale[sale[0]] = sale[1]
		date_last_sales = {}
		for (t, d) in last_sale.items():
			if d not in date_last_sales:
				date_last_sales[d] = [t]
			else:
				date_last_sales[d].append(t)
		balance = 0
		required = [0] + k.copy()
		end = 0
		for d in range(1, days + 1):
			balance += 1
			if d in date_last_sales:
				for t in date_last_sales[d]:
					if required[t] > 0:
						if required[t] > balance:
							end += required[t] - balance
						balance -= min(required[t], balance)
						required[t] = 0
			if d == days:
				for r in required:
					if r > 0:
						end += r
		return 2 * end <= balance
	total = sum(k)
	hi = 2 * total
	lo = 1
	while lo + 1 < hi:
		mid = (lo + hi) // 2
		if check(mid):
			hi = mid
		else:
			lo = mid
	if check(lo):
		print(lo)
	else:
		print(hi)
main()


def check(mid):
	l = [0 for i in range(n)]
	for i in b:
		if i[0] > mid:
			break
		l[i[1] - 1] = i[0]
	v = [0 for i in range(mid + 1)]
	for i in range(n):
		v[l[i]] += a[i]
	ct = 0
	for i in range(1, mid + 1):
		ct += 1
		if ct >= v[i]:
			ct -= v[i]
			v[i] = 0
		else:
			v[i] -= ct
			ct = 0
	return ct >= 2 * sum(v)

def bs():
	l = 0
	r = 5 * 10 ** 5
	while l <= r:
		mid = (l + r) // 2
		if check(mid):
			r = mid - 1
		else:
			l = mid + 1
	return r + 1
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = []
for i in range(m):
	b.append(list(map(int, input().split())))
b.sort()
print(bs())


import sys
import bisect
import copy
input = sys.stdin.readline
(n, m) = map(int, input().split())
K = [0] + list(map(int, input().split()))
SP = [list(map(int, input().split())) for i in range(m)]
SP2 = [[] for i in range(n + 1)]
for (d, t) in SP:
	SP2[t].append(d)
for i in range(n + 1):
	SP2[i].sort()
SUM = sum(K)
MIN = SUM
MAX = SUM * 2
MAXBUY = 0
while MIN != MAX:
	day = (MIN + MAX) // 2
	DAYS = [[] for i in range(day + 1)]
	for i in range(n + 1):
		x = bisect.bisect_right(SP2[i], day) - 1
		if x >= 0:
			DAYS[SP2[i][x]].append(i)
	GOLD = 0
	SUMK = SUM
	K2 = copy.deepcopy(K)
	for d in range(1, day + 1):
		GOLD += 1
		for t in DAYS[d]:
			DBUY = min(K2[t], GOLD, SUMK)
			K2[t] -= DBUY
			GOLD -= DBUY
	if GOLD >= sum(K2) * 2:
		MAX = day
	else:
		MIN = day + 1
print(MIN)


import sys
import copy
DEBUG = False
if DEBUG:
	inf = open('input.txt')
else:
	inf = sys.stdin
(N, M) = list(map(int, inf.readline().split(' ')))
n_items = list(map(int, inf.readline().split(' ')))
sales = []
for _ in range(M):
	sale = list(map(int, inf.readline().split(' ')))
	sales.append(sale)
sales = sorted(sales, key=lambda x: x[0], reverse=True)

def can_buy_in(dday):
	used = 0
	money_left = dday
	items = n_items[:]
	for (sale_day, sale_type) in sales:
		if sale_day > dday:
			continue
		if money_left > sale_day:
			money_left = sale_day
		can_buy = min(items[sale_type - 1], money_left)
		used += can_buy
		items[sale_type - 1] -= can_buy
		money_left -= can_buy
		if money_left == 0:
			break
	need_money_for_rest = sum(items) * 2
	return need_money_for_rest + used <= dday
total_items = sum(n_items)
low = total_items
high = total_items * 2
while low <= high:
	mid = (low + high) // 2
	if can_buy_in(mid):
		high = mid - 1
	else:
		low = mid + 1
print(low)


def BinarySearch(my_list, key):
	l = 0
	r = len(my_list) - 1
	while r > l:
		mid = (l + r) // 2
		if my_list[mid + 1] <= key:
			l = mid + 1
		else:
			r = mid
	return l

def weather_can_buy(day, total, req_list, sale_days):
	tmp_buy = []
	last_day = []
	d = day
	my_total = total
	for i in range(len(req_list)):
		last_day.append(0)
	for i in range(d):
		tmp_buy.append(0)
	for i in range(len(sale_days)):
		if len(sale_days[i]) > 0:
			index = BinarySearch(sale_days[i], day)
			last_day[i] = sale_days[i][index]
	for i in range(len(last_day)):
		if last_day[i] - 1 > -1:
			tmp_buy[last_day[i] - 1] += req_list[i]
	money = 0
	for i in range(d):
		money += 1
		my_total -= min(money, tmp_buy[i])
		money -= min(money, tmp_buy[i])
	if my_total < 0:
		return True
	elif money >= my_total * 2:
		return True
	else:
		return False

def function():
	tmp = input().split(' ')
	n = int(tmp[0])
	m = int(tmp[1])
	req_list = input().split(' ')
	req_list = list(map(int, req_list))
	total = sum(req_list)
	sale_days = []
	for i in range(len(req_list)):
		sale_days.append([0])
	for i in range(m):
		tmp = input().split(' ')
		(dj, tj) = (int(tmp[0]), int(tmp[1]))
		sale_days[tj - 1].append(dj)
	for i in range(len(sale_days)):
		sale_days[i] = sorted(sale_days[i])
	for i in range(len(sale_days)):
		sale_days[i] = sorted(sale_days[i])
	l = 1
	r = 2 * total
	while r > l:
		mid = (l + r) // 2
		if weather_can_buy(mid, total, req_list, sale_days):
			r = mid
		else:
			l = mid + 1
	print(r)
function()


import sys
input = sys.stdin.readline

def check(num):
	last = [0 for i in range(n)]
	for i in o:
		if i[0] > num:
			break
		else:
			last[i[1] - 1] = i[0]
	b = [0 for i in range(num + 1)]
	for i in range(n):
		b[last[i]] += a[i]
	i = 0
	c = 0
	d = 0
	for i in range(1, num + 1):
		c += 1
		if c >= b[i]:
			c -= b[i]
			b[i] = 0
		else:
			b[i] -= c
			c = 0
	s = sum(b)
	if s * 2 <= c:
		return True
	return False
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
o = []
for i in range(m):
	(x, y) = map(int, input().split())
	o.append((x, y))
o.sort()
low = 1
high = sum(a) * 2
while low < high:
	mid = (low + high) // 2
	if check(mid):
		high = mid - 1
	else:
		low = mid + 1
if check(low):
	print(low)
else:
	print(low + 1)


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
BUFSIZE = 8192

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.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
		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):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

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

class SegmentTree1:

	def __init__(self, data, default=10 ** 6, func=lambda a, b: min(a, b)):
		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):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
MOD = 10 ** 9 + 7

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(10)]
pp = [0] * 10

def SieveOfEratosthenes(n=10):
	p = 2
	c = 0
	while p * p <= n:
		if prime[p] == True:
			c += 1
			for i in range(p, n + 1, p):
				pp[i] += 1
				prime[i] = False
		p += 1

def binarySearch(arr, n, key):
	left = 0
	right = n - 1
	mid = 0
	res = 0
	while left <= right:
		mid = (right + left) // 2
		if arr[mid][0] > key:
			right = mid - 1
		else:
			res = mid
			left = mid + 1
	return res
(n, m) = map(int, input().split())
l = list(map(int, input().split()))
t = []
for i in range(m):
	(a, b) = map(int, input().split())
	t.append((a, b))
t.sort()

def check(x):
	now = x
	c = sum(l)
	cur = 0
	last = 0
	ld = defaultdict(int)
	for i in range(len(t)):
		if t[i][0] <= x:
			ld[t[i][1]] = i
	for i in range(m):
		if ld[t[i][1]] != i:
			continue
		if t[i][0] > x:
			break
		cur += t[i][0] - last
		rt = min(cur, l[t[i][1] - 1])
		cur -= rt
		now -= rt
		c -= rt
		last = t[i][0]
	if now >= 2 * c:
		return True
	return False
st = 1
end = 2 * sum(l)
ans = end
while st <= end:
	mid = (st + end) // 2
	if check(mid) == True:
		ans = mid
		end = mid - 1
	else:
		st = mid + 1
print(ans)


import sys
(N, M) = [int(x) for x in sys.stdin.readline().rstrip().split()]
K = [int(x) for x in sys.stdin.readline().rstrip().split()]
D = [0] * M
T = [0] * M
for i in range(M):
	(D[i], T[i]) = [int(x) for x in sys.stdin.readline().rstrip().split()]
	D[i] -= 1
	T[i] -= 1
KS = sum(K)
ok = 2 * KS
ng = KS - 1
while ok - ng > 1:
	X = (ok + ng) // 2
	last = [-1] * N
	for i in range(M):
		if last[T[i]] < D[i] < X:
			last[T[i]] = D[i]
	l2i = [[] for i in range(X)]
	for i in range(N):
		if last[i] != -1:
			l2i[last[i]].append(i)
	buy = 0
	now = 0
	for i in range(X):
		now += 1
		for j in l2i[i]:
			s = now if now < K[j] else K[j]
			now -= s
			buy += s
	buy += now // 2
	if buy >= KS:
		ok = X
	else:
		ng = X
print(ok)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

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.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 30, func=lambda a, b: min(a, b)):
		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):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

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

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		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):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

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

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] > k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += 1
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += 1
		self.temp.data = pre_xor

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data
(n, m) = map(int, input().split())
l = list(map(int, input().split()))
t = []
for i in range(m):
	(a, b) = map(int, input().split())
	t.append((a, b))
t.sort()

def check(x):
	now = x
	c = sum(l)
	cur = 0
	last = 0
	ld = defaultdict(int)
	for i in range(len(t)):
		if t[i][0] <= x:
			ld[t[i][1]] = i
	for i in range(m):
		if ld[t[i][1]] != i:
			continue
		if t[i][0] > x:
			break
		cur += t[i][0] - last
		rt = min(cur, l[t[i][1] - 1])
		cur -= rt
		now -= rt
		c -= rt
		last = t[i][0]
	if now >= 2 * c:
		return True
	return False
st = 1
end = 2 * sum(l)
ans = end
while st <= end:
	mid = (st + end) // 2
	if check(mid) == True:
		ans = mid
		end = mid - 1
	else:
		st = mid + 1
print(ans)


import collections

def main():
	from sys import stdin, stdout

	def read():
		return stdin.readline().rstrip('\n')

	def read_array(sep=None, maxsplit=-1):
		return read().split(sep, maxsplit)

	def read_int():
		return int(read())

	def read_int_array(sep=None, maxsplit=-1):
		return [int(a) for a in read_array(sep, maxsplit)]

	def write(*args, **kwargs):
		sep = kwargs.get('sep', ' ')
		end = kwargs.get('end', '\n')
		stdout.write(sep.join((str(a) for a in args)) + end)

	def write_array(array, **kwargs):
		sep = kwargs.get('sep', ' ')
		end = kwargs.get('end', '\n')
		stdout.write(sep.join((str(a) for a in array)) + end)

	def enough(days):
		bought = []
		bought_total = 0
		used_from = days
		for d in range(days, 0, -1):
			used_from = min(d, used_from)
			for t in offers.get(d, []):
				if K[t] > 0:
					x = min(K[t], used_from)
					K[t] -= x
					bought.append((t, x))
					bought_total += x
					used_from -= x
			if not used_from:
				break
		remaining_money = days - bought_total
		ans = (total_transaction - bought_total) * 2 <= remaining_money
		for (t, a) in bought:
			K[t] += a
		return ans
	(n, m) = read_int_array()
	K = read_int_array()
	total_transaction = sum(K)
	offers = collections.defaultdict(list)
	for _ in range(m):
		(d, t) = read_int_array()
		offers[d].append(t - 1)
	low = total_transaction
	high = low * 2
	ans = high
	while low <= high:
		mid = (low + high) // 2
		if enough(mid):
			ans = mid
			high = mid - 1
		else:
			low = mid + 1
	write(ans)
main()