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 1000$) — 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 1000$), 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 $1000$.

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 1000, 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 os
from io import BytesIO

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
	os.write(1, str(lo).encode())
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
main()


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
for day in range(MIN, MAX + 1):
	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:
		print(day)
		break


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()


from collections import defaultdict

def possible(days):
	nonlocal events, k
	latest_ev = defaultdict(int)
	for (d, t) in events:
		if d <= days:
			latest_ev[t] = max(latest_ev[t], d)
	earned = days
	offers_needed = 2 * sum(k) - earned
	offers = 0
	cur_day = 0
	cur_val = 0
	for (t, d) in sorted(list(latest_ev.items()), key=lambda x: x[1]):
		cur_val += d - cur_day
		cur_day = d
		offers_to_take = min(k[t], cur_val)
		offers += offers_to_take
		cur_val -= offers_to_take
		if offers >= offers_needed:
			return True
	return offers >= offers_needed
(n, m) = list(map(int, input().split()))
k = list(map(int, input().split()))
events = []
for _ in range(m):
	(d, t) = list(map(int, input().split()))
	t -= 1
	events.append((d, t))
lo = sum(k) - 1
hi = 2 * sum(k)
while lo + 1 < hi:
	mid = (lo + hi) // 2
	if possible(mid):
		hi = mid
	else:
		lo = mid
print(hi)


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)
	for i in range(1, 2 * total + 1):
		if check(i):
			print(i)
			break
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 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 = copy.deepcopy(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)


import sys
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])
last_sales = {k: -1 for k in range(N + 1)}
final_sol = 99999999
for i in range(M):
	(sale_day, sale_type) = sales[i]
	last_sales[sale_type] = sale_day
	if i != M - 1:
		if sales[i + 1][0] == sale_day:
			continue
	total = 0
	lasts = last_sales.items()
	lasts = sorted(lasts, key=lambda x: x[1])
	burle = 0
	before_lastday = -1
	for (stype, last_sday) in lasts:
		if stype == 0:
			continue
		if last_sday == -1:
			total += n_items[stype - 1] * 2
			continue
		if before_lastday == -1:
			burle = last_sday
		else:
			burle += last_sday - before_lastday
		before_lastday = last_sday
		bought = min(burle, n_items[stype - 1])
		left = n_items[stype - 1] - bought
		burle -= bought
		total += bought + 2 * left
	sol = max(sale_day, total)
	if final_sol > sol:
		final_sol = sol
print(final_sol)


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 os
from io import BytesIO, IOBase
_str = str
str = lambda x=b'': x if type(x) is bytes else _str(x).encode()

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._buffer = BytesIO()
		self._fd = file.fileno()
		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):
		if self._buffer.tell():
			return self._buffer.read()
		return os.read(self._fd, os.fstat(self._fd).st_size)

	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))

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', b' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', b'\n'))
	if kwargs.pop('flush', False):
		file.flush()
BUFSIZE = 8192
(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
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])
last_sales = {k: -1 for k in range(N + 1)}
final_sol = 99999999
for i in range(M):
	(sale_day, sale_type) = sales[i]
	last_sales[sale_type] = sale_day
	if i != M - 1:
		if sales[i + 1][0] == sale_day:
			continue
	total = 0
	lasts = last_sales.items()
	lasts = sorted(lasts, key=lambda x: x[1])
	burle = 0
	before_lastday = -1
	for (stype, last_sday) in lasts:
		if stype == 0:
			continue
		if last_sday == -1:
			total += n_items[stype - 1] * 2
			continue
		if before_lastday == -1:
			burle = last_sday
		else:
			burle += last_sday - before_lastday
		before_lastday = last_sday
		bought = min(burle, n_items[stype - 1])
		left = n_items[stype - 1] - bought
		burle -= bought
		total += bought + 2 * left
	sol = max(sale_day, total)
	if final_sol > sol:
		final_sol = sol
print(final_sol)


(n, m) = input().split()
n = int(n)
m = int(m)
nList = input().split()
bList = [0] * len(nList)
for i in range(len(nList)):
	nList[i] = int(nList[i])
shopD = {}
shopT = {}
oHis = []
mHis = []
maxD = 0
for i in range(m):
	(d, t) = input().split()
	if nList[int(t) - 1] != 0:
		maxD = max(maxD, int(d))
		if d not in shopD.keys():
			shopD.update({d: [int(t)]})
		elif int(t) not in shopD[d]:
			shopD[d].append(int(t))
		if t not in shopT.keys():
			shopT.update({t: [int(d)]})
		elif int(d) not in shopT[t]:
			shopT[t].append(int(d))
for (i, j) in shopT.items():
	j = list(dict.fromkeys(j))
	j.sort()
	shopT[i] = j
for (i, j) in shopD.items():
	j = list(dict.fromkeys(j))
	shopD[i] = j
total = sum(nList)
coin = 0
day = 0

def modifyMis(t, left):
	if left == 0:
		for ii in range(len(mHis))[::-1]:
			if mHis[ii]['t'] == t:
				mHis.pop(ii)
	else:
		for ii in range(len(mHis))[::-1]:
			if mHis[ii]['t'] == t:
				mHis[ii]['n'] = left
while total > 0 and day < maxD:
	coin += 1
	day += 1
	oHis.append({'t': [], 'n': []})
	if str(day) in shopD.keys():
		for t in shopD[str(day)]:
			if nList[t - 1] > 0:
				if bList[t - 1] > 0 and shopT[str(t)][0] != day and (coin > nList[t - 1] - bList[t - 1]) and (len(mHis) > 0) and (coin > 0):
					i = 0
					j = 0
					while shopT[str(t)][i] < day:
						extraC = 0
						d = shopT[str(t)][i]
						if t in oHis[d - 1]['t']:
							indexT = oHis[d - 1]['t'].index(t)
							extraC += oHis[d - 1]['n'][indexT]
							bList[t - 1] -= oHis[d - 1]['n'][indexT]
							total += oHis[d - 1]['n'][indexT]
							oHis[d - 1]['t'].pop(indexT)
							oHis[d - 1]['n'].pop(indexT)
						while j < len(mHis) and mHis[j]['d'] < d:
							j += 1
						while extraC > 0 and len(mHis) > j:
							thisT = mHis[j]['t']
							thisD = mHis[j]['d']
							change = min(extraC, mHis[j]['n'])
							bList[thisT - 1] += change
							total -= change
							extraC -= change
							mHis[j]['n'] -= change
							modifyMis(thisT, nList[thisT - 1] - bList[thisT - 1])
							if thisT in oHis[thisD - 1]['t']:
								oHis[thisD - 1]['n'][oHis[thisD - 1]['t'].index(thisT)] += change
							else:
								oHis[thisD - 1]['t'].append(thisT)
								oHis[thisD - 1]['n'].append(change)
						i += 1
						coin += extraC
			buy = min(nList[t - 1] - bList[t - 1], coin)
			if buy != 0:
				oHis[day - 1]['t'].append(t)
				oHis[day - 1]['n'].append(buy)
				total -= buy
				bList[t - 1] += buy
				modifyMis(t, nList[t - 1] - bList[t - 1])
				coin -= buy
			if nList[t - 1] - bList[t - 1] > 0:
				mHis.append({'d': day, 't': t, 'n': nList[t - 1] - bList[t - 1]})
	if coin >= total * 2:
		break
day += max(total * 2 - coin, 0)
print(day)


import copy
from collections import defaultdict
BIG = 10 ** 9
(N, M) = [int(i) for i in input().split()]
K = [0] + [int(i) for i in input().split()]
sumK = sum(K)
max_days = 2 * sum(K)
day_at_sale_per_item = defaultdict(list)
for i in range(M):
	(day, item) = [int(i) for i in input().split()]
	day_at_sale_per_item[item].append(day)
sales_per_day = defaultdict(list)
for (item, days) in day_at_sale_per_item.items():
	for day in days:
		sales_per_day[day].append(item)
(L, R) = (0, max_days)
answer = 0
while L <= R:
	m = (L + R) // 2

	def get_best_sales(m):
		best_sales = defaultdict(list)
		for (item, days) in day_at_sale_per_item.items():
			best_day = 0
			for day in days:
				if day <= m:
					best_day = max(best_day, day)
			if best_day:
				best_sales[best_day].append(item)
		return best_sales

	def available_sales(m):
		available_money = 0
		nb_sales = 0
		cK = copy.deepcopy(K)
		best_sales = get_best_sales(m)
		for day in range(1, m + 1):
			available_money += 1
			for item in best_sales[day]:
				buy = min(cK[item], available_money)
				if buy:
					cK[item] -= buy
					available_money -= buy
					nb_sales += buy
		return nb_sales

	def possible(m):
		total_money = m
		needed_money = 2 * sumK - available_sales(m)
		return total_money >= needed_money
	if possible(m):
		answer = m
		R = m - 1
	else:
		L = m + 1
print(answer)


def main():
	inp = readnumbers()
	ii = 0
	n = inp[ii]
	ii += 1
	m = inp[ii]
	ii += 1
	K = inp[ii:n + ii]
	ii += n
	types = [[] for _ in range(n)]
	for _ in range(m):
		types[inp[ii + 1] - 1].append(inp[ii] - 1)
		ii += 2
	needed = sum(K)
	nonzero = [t for t in range(n) if K[t] > 0 and types[t]]
	for t in nonzero:
		types[t].sort()
	a = 0
	b = 4 * 10 ** 5 + 10
	extra = [0] * b
	while a < b:
		mid = (a + b) // 2
		for t in nonzero:
			A = types[t]
			ind = len(A)
			while ind and A[ind - 1] >= mid:
				ind -= 1
			if ind:
				extra[A[ind - 1]] += K[t]
		bought = 0
		money = 0
		for d in range(mid):
			money += 1
			if extra[d]:
				amount = min(money, extra[d])
				money -= amount
				bought += amount
			extra[d] = 0
		left = needed - bought
		if money >= left * 2:
			b = mid
		else:
			a = mid + 1
	print(a)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			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')
import sys

class ostream:

	def __lshift__(self, a):
		sys.stdout.write(str(a))
		return self
cout = ostream()
endl = '\n'

def readnumbers(zero=0):
	conv = ord if py2 else lambda x: x
	A = []
	numb = zero
	sign = 1
	i = 0
	s = sys.stdin.buffer.read()
	try:
		while True:
			if s[i] >= b'0'[0]:
				numb = 10 * numb + conv(s[i]) - 48
			elif s[i] == b'-'[0]:
				sign = -1
			elif s[i] != b'\r'[0]:
				A.append(sign * numb)
				numb = zero
				sign = 1
			i += 1
	except:
		pass
	if s and s[-1] >= b'0'[0]:
		A.append(sign * numb)
	return A
main()


import sys
import os
from io import BytesIO
DEBUG = False
if DEBUG:
	inf = open('input.txt')
else:
	inf = BytesIO(os.read(0, os.fstat(0).st_size))
(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)


from collections import deque

def main():
	(n, m) = list(map(int, input().split()))
	wanted_cnt = list(map(int, input().split()))
	Order = [tuple(map(int, input().split())) for i in range(m)]
	S = sum(wanted_cnt)

	def ispossible_within(Day):
		sale_get_cnt = 0
		last_sale = [0] * n
		for (day, good) in Order:
			if day > Day:
				continue
			last_sale[good - 1] = max(last_sale[good - 1], day)
		Que = []
		for i in range(n):
			if wanted_cnt[i] > 0 and last_sale[i] > 0:
				Que.append((last_sale[i], wanted_cnt[i]))
		Que.sort()
		que = deque(Que)
		while que:
			(sale_day, wanted) = que.popleft()
			money_left = sale_day - sale_get_cnt
			if money_left >= wanted:
				sale_get_cnt += wanted
			elif money_left < wanted:
				sale_get_cnt += money_left
		left_money = Day - sale_get_cnt
		left = S - sale_get_cnt
		return left_money >= 2 * left
	impossible = 0
	possible = 2020
	while possible - impossible > 1:
		m = (impossible + possible) // 2
		if ispossible_within(m):
			possible = m
		else:
			impossible = m
	print(possible)
	return

def __starting_point():
	main()
__starting_point()


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
else:
	_str = str
	str = lambda x=b'': x if type(x) is bytes else _str(x).encode()

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)

	def cond(x):
		cash = x
		offset = 0
		_k = k[:]
		for i in reversed(range(x)):
			for j in d[i]:
				while cash and _k[j]:
					_k[j] -= 1
					cash -= 1
			if cash == i + 1:
				cash -= 2
				offset += 1
		return 2 * (sum(_k) - offset) <= cash
	(lo, hi) = (0, 4 * 10 ** 5 + 1)
	while lo < hi:
		mi = (hi + lo) // 2
		if cond(mi):
			hi = mi
		else:
			lo = mi + 1
	print(lo)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._buffer = BytesIO()
		self._fd = file.fileno()
		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):
		if self._buffer.tell():
			return self._buffer.read()
		return os.read(self._fd, os.fstat(self._fd).st_size)

	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))

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', b' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', b'\n'))
	if kwargs.pop('flush', False):
		file.flush()
(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
input = lambda : sys.stdin.readline().rstrip(b'\r\n')
main()


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 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 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()