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.

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.

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

import java.util.*;

public class Solution
{
       static int k[];
       static int offer[][];

       static boolean check(int x)
       {

              int o[] = new int[1001];
              int money = 0;
              int total = 0;
              for(int i = 0 ; i < offer.length ; i++)
              {

                     if(offer[i][0] > o[offer[i][1]] && offer[i][0] <= x)
                     o[offer[i][1]] = offer[i][0];
              }

              for(int i = 0 ; i < Math.min(1000,x) ; i++)
              {
                     money++;
                     for(int j = 1 ; j <= k.length ; j++)
                     {

                           if(o[j] != 0 && o[j] == i+1)
                           {
                                  total += Math.min(money , k[j-1]);
                            money = Math.max(0 , money-k[j-1]);

                           }

                     }

              }
              int T = 0;
              for(int i = 0 ; i < k.length ; i++)
              {
                     T += k[i];
              }
              T -= total;

             if(x > 1000)
             money = money+x-1000;

              if(money >= 2*T)
              return true;

              return false;
       }
       public static void main(String []args)
       {
              Scanner sc = new Scanner(System.in);
              int n = sc.nextInt();
              int m = sc.nextInt();
              k = new int[n];
              for(int i = 0 ; i < n ; i++)
              {
                     k[i] = sc.nextInt();
              }
              offer = new int[m][2];
              for(int i = 0 ; i < m ; i++)
              {
                     offer[i][0] = sc.nextInt();
                     offer[i][1] = sc.nextInt();
              }
              int l = 1 , r = 1000000;
             while(l <  r)
              {
                     int mid = (l+r)/2;
                     boolean c = check(mid);
                     if(c)
                     r = mid;

                     else
                     l = mid+1;

              }

            System.out.println(l);
       }
}

import java.io.*;
import java.util.*;

public class b
{
    public static void print(String str,long val){
        System.out.println(str+"  "+val);
    }

    public long gcd(long a, long b) {
        if (b==0L) return a;
        return gcd(b,a%b);
    }

    public static void debug(long[][] arr){
        int len = arr.length;
        for(int i=0;i<len;i++){
            System.out.println(Arrays.toString(arr[i]));
        }
    }
    public static void debug(int[][] arr){
        int len = arr.length;
        for(int i=0;i<len;i++){
            System.out.println(Arrays.toString(arr[i]));
        }
    }
    public static void debug(String[] arr){
        int len = arr.length;
        for(int i=0;i<len;i++){
            System.out.println(arr[i]);
        }
    }

    public static void print(int[] arr){
        int len = arr.length;
        for(int i=0;i<len;i++){
            System.out.print(arr[i]+" ");
        }
        System.out.print('\n');
    }

    public static void print(Object[] arr){
        int len = arr.length;
        for(int i=0;i<len;i++){
            System.out.print(arr[i]+" ");
        }
        System.out.print('\n');
    }
    public static void print(String[] arr){
        int len = arr.length;
        for(int i=0;i<len;i++){
            System.out.print(arr[i]+" ");
        }
        System.out.print('\n');
    }
    public static void print(long[] arr){
        int len = arr.length;
        for(int i=0;i<len;i++){
            System.out.print(arr[i]+" ");
        }
        System.out.print('\n');
    }

    static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                    InputStreamReader(System.in));
        }
        public FastReader(String path) throws FileNotFoundException {
            br = new BufferedReader(new FileReader(path));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }

    static void sort(long[] arr){
        Long[] temp = new Long[arr.length];
        for(int i=0;i<arr.length;i++){
            temp[i] = arr[i];
        }
        Arrays.sort(temp);
        for(int i=0;i<arr.length;i++){
            arr[i] = temp[i];
        }
    }

    static int[] copies;
    static pair[] days;
    static int n;
    static int m;
    public static void main(String[] args)
    {
        FastReader s=new FastReader();
        n = s.nextInt();
        m = s.nextInt();
        copies = new int[n];
        for(int i=0;i<n;i++){
            copies[i] = s.nextInt();
        }
        days = new pair[m];
        for (int i=0;i<m;i++){
            int day = s.nextInt();
            int type = s.nextInt()-1;
            days[i] = new pair(day,type);
        }
        Arrays.sort(days);
        int start =1;
        int end = 2*(1000);
        while (end-start>1){
            int mid = (end+start)/2;
            if(check(mid)){
                end = mid;
            }
            else start = mid+1;
        }
        if(check(start)) System.out.println(start);
        else System.out.println(end);
//        check(5);

    }

    static boolean check(int k){
        boolean[] visited = new boolean[n];
        ArrayList<Integer>[] last_day = new ArrayList[k+1];
        for(int i=0;i<=k;i++){
            last_day[i] = new ArrayList<>();
        }
        for(int i=m-1;i>=0;i--){
            if(days[i].day>k){
                continue;
            }
            else {
                if(!visited[days[i].type]){
                    visited[days[i].type] = true;
                    last_day[days[i].day].add(days[i].type);
                }
            }
        }
//        print(last_day);
        int cost =0;
        int[] required = copies.clone();
        for(int i=1;i<=k;i++){
            if(last_day[i].size()==0){
                cost++;
            }
            else {
                cost++;
                for(int child:last_day[i]){
                    if(required[child]>0){
                        if(cost>=required[child]){
                            cost-=required[child];
                            required[child] =0;
                        }
                        else {
                            int temp = Math.min(cost,required[child]);
                            cost-=temp;
                            required[child]-=temp;
                        }
                    }
                }
            }

        }
        int total =0;
        for(int i=0;i<n;i++){
            total+=required[i];
        }
        if(cost>=2*total){
            return true;
        }
        return false;
    }

    static class pair implements  Comparable<pair>{
        int day;
        int type;
        pair(int day,int type) {
            this.day = day;
            this.type = type;
        }
        public int compareTo(pair p){
            return Integer.compare(this.day,p.day);
        }
    }

//    OutputStream out = new BufferedOutputStream( System.out );
//        for(int i=1;i<n;i++){
//              out.write((arr[i]+" ").getBytes());
//         }
//        out.flush();
//  long start_time = System.currentTimeMillis();
//  long end_time = System.currentTimeMillis();
//  System.out.println((end_time - start_time) + "ms");

}

/*
    Author: Anthony Ngene
    Created: 04/10/2020 - 12:56
*/

import java.io.*;
import java.util.*;

public class F {
// checks: 1. edge cases   2. overflow   3. possible errors (e.g 1/0, arr[out])   4. time/space complexity
    int n;
    int m;
    int[] arr;
    int required;
    HashMap<Integer, TreeSet<Integer>> typeDays;
    void solver() throws IOException {
        n = in.intNext(); m = in.intNext();
        arr = in.nextIntArray(n);
        required = sum(arr);
        typeDays = new HashMap<>();
        for (int i = 0; i < m; i++) {
            int d = in.intNext(), typ = in.intNext();
            if (arr[typ - 1] <= 0) continue;
            if (!typeDays.containsKey(typ)) typeDays.put(typ, new TreeSet<>());
            typeDays.get(typ).add(d);
        }

        int lo = required;
        int hi = 2 * required;
        int valid = hi;
        while (lo <= hi) {
            int mid = (lo + hi) / 2;
            if (isEnough(mid)) {
                valid = mid;
                hi = mid - 1;
            } else
                lo = mid + 1;
        }
        out.println(valid);
    }

    boolean isEnough(int day) {
        int totalCoin = day;
        int req = required;

        int[] ddays = new int[day + 1];
        for (int typ : typeDays.keySet()) {
            Integer lastDay = typeDays.get(typ).floor(day);
            if (lastDay == null) continue;
            ddays[lastDay] += arr[typ - 1];
        }
//        out.println(ddays);
        int removed = 0;
        for (int i = 1; i < day + 1; i++) {
            int coins = i - removed;
            int toRemove = min(coins, ddays[i]);
            removed += toRemove;
            totalCoin -= toRemove;
            req -= toRemove;
        }
//        out.pp(req, totalCoin);
        return req * 2 <= totalCoin;
    }

// Generated Code Below:
private static final FastWriter out = new FastWriter();
private static FastScanner in;
static ArrayList<Integer>[] adj;
private static long e97 = (long)1e9 + 7;
public static void main(String[] args) throws IOException {
    in = new FastScanner();
    new F().solver();
    out.close();
}

static class FastWriter {
    private static final int IO_BUFFERS = 128 * 1024;
    private final StringBuilder out;
    public FastWriter() { out = new StringBuilder(IO_BUFFERS); }
    public FastWriter p(Object object) { out.append(object); return this; }
    public FastWriter p(String format, Object... args) { out.append(String.format(format, args)); return this; }
    public FastWriter pp(Object... args) { for (Object ob : args) { out.append(ob).append(" ");  } out.append("\n"); return this; }
    public FastWriter pp(int[] args) { for (int ob : args) { out.append(ob).append(" ");  } out.append("\n"); return this; }
    public FastWriter pp(long[] args) { for (long ob : args) { out.append(ob).append(" ");  } out.append("\n"); return this; }
    public FastWriter pp(char[] args) { for (char ob : args) { out.append(ob).append(" ");  } out.append("\n"); return this; }
    public void println(long[] arr) { for(long e: arr) out.append(e).append(" "); out.append("\n"); }
    public void println(int[] arr) { for(int e: arr) out.append(e).append(" "); out.append("\n"); }
    public void println(char[] arr) { for(char e: arr) out.append(e).append(" "); out.append("\n"); }
    public void println(double[] arr) { for(double e: arr) out.append(e).append(" "); out.append("\n"); }
    public void println(boolean[] arr) { for(boolean e: arr) out.append(e).append(" "); out.append("\n"); }
    public <T>void println(T[] arr) { for(T e: arr) out.append(e).append(" "); out.append("\n"); }
    public void println(long[][] arr) {  for (long[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
    public void println(int[][] arr) {  for (int[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
    public void println(char[][] arr) {  for (char[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
    public void println(double[][] arr) {  for (double[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
    public <T>void println(T[][] arr) {  for (T[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
    public FastWriter println(Object object) { out.append(object).append("\n"); return this; }
    public void toFile(String fileName) throws IOException {
        BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
        writer.write(out.toString());
        writer.close();
    }
    public void close() throws IOException { System.out.print(out); }
}
static class FastScanner {
    private InputStream sin = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;
    public FastScanner(){}
    public FastScanner(String filename) throws FileNotFoundException {
        File file = new File(filename);
        sin = new FileInputStream(file);
    }
    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        }else{
            ptr = 0;
            try {
                buflen = sin.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }
    private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
    private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
    public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
    public String next() {
        if (!hasNext()) throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while(isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }
    public long longNext() {
        if (!hasNext()) throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while(true){
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            }else if(b == -1 || !isPrintableChar(b) || b == ':'){
                return minus ? -n : n;
            }else{
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }
    public int intNext() {
        long nl = longNext();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
        return (int) nl;
    }
    public double doubleNext() { return Double.parseDouble(next());}
    public long[] nextLongArray(final int n){
        final long[] a = new long[n];
        for (int i = 0; i < n; i++)
            a[i] = longNext();
        return a;
    }
    public int[] nextIntArray(final int n){
        final int[] a = new int[n];
        for (int i = 0; i < n; i++)
            a[i] = intNext();
        return a;
    }
    public double[] nextDoubleArray(final int n){
        final double[] a = new double[n];
        for (int i = 0; i < n; i++)
            a[i] = doubleNext();
        return a;
    }
    public ArrayList<Integer>[] getAdj(int n) {
        ArrayList<Integer>[] adj = new ArrayList[n + 1];
        for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>();
        return adj;
    }
    public ArrayList<Integer>[] adjacencyList(int nodes, int edges) throws IOException {
        return adjacencyList(nodes, edges, false);
    }
    public ArrayList<Integer>[] adjacencyList(int nodes, int edges, boolean isDirected) throws IOException {
        adj = getAdj(nodes);
        for (int i = 0; i < edges; i++) {
            int a = intNext(), b = intNext();
            adj[a].add(b);
            if (!isDirected) adj[b].add(a);
        }
        return adj;
    }
}
static class u {
    public static int upperBound(long[] array, long obj) {
        int l = 0, r = array.length - 1;
        while (r - l >= 0) {
            int c = (l + r) / 2;
            if (obj < array[c]) {
                r = c - 1;
            } else {
                l = c + 1;
            }
        }
        return l;
    }
    public static int upperBound(ArrayList<Long> array, long obj) {
        int l = 0, r = array.size() - 1;
        while (r - l >= 0) {
            int c = (l + r) / 2;
            if (obj < array.get(c)) {
                r = c - 1;
            } else {
                l = c + 1;
            }
        }
        return l;
    }
    public static int lowerBound(long[] array, long obj) {
        int l = 0, r = array.length - 1;
        while (r - l >= 0) {
            int c = (l + r) / 2;
            if (obj <= array[c]) {
                r = c - 1;
            } else {
                l = c + 1;
            }
        }
        return l;
    }
    public static int lowerBound(ArrayList<Long> array, long obj) {
        int l = 0, r = array.size() - 1;
        while (r - l >= 0) {
            int c = (l + r) / 2;
            if (obj <= array.get(c)) {
                r = c - 1;
            } else {
                l = c + 1;
            }
        }
        return l;
    }
    static <T> T[][] deepCopy(T[][] matrix) { return Arrays.stream(matrix).map(el -> el.clone()).toArray($ -> matrix.clone()); }
    static int[][] deepCopy(int[][] matrix) { return Arrays.stream(matrix).map(int[]::clone).toArray($ -> matrix.clone()); }
    static long[][] deepCopy(long[][] matrix) { return Arrays.stream(matrix).map(long[]::clone).toArray($ -> matrix.clone()); }
    private static void sort(int[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); }
    private static void sort(long[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); }
    private static <T>void rSort(T[] arr) { Arrays.sort(arr, Collections.reverseOrder()); }
    private static void customSort(int[][] arr) {
        Arrays.sort(arr, new Comparator<int[]>() {
            public int compare(int[] a, int[] b) {
                if (a[0] == b[0]) return Integer.compare(a[1], b[1]);
                return Integer.compare(a[0], b[0]);
            }
        });
    }
    public static int[] swap(int[] arr, int left, int right) {
        int temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;
        return arr;
    }
    public static char[] swap(char[] arr, int left, int right) {
        char temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;
        return arr;
    }
    public static int[] reverse(int[] arr, int left, int right) {
        while (left < right) {
            int temp = arr[left];
            arr[left++] = arr[right];
            arr[right--] = temp;
        }
        return arr;
    }
    public static boolean findNextPermutation(int[] data) {
        if (data.length <= 1) return false;
        int last = data.length - 2;
        while (last >= 0) {
            if (data[last] < data[last + 1]) break;
            last--;
        }
        if (last < 0) return false;
        int nextGreater = data.length - 1;
        for (int i = data.length - 1; i > last; i--) {
            if (data[i] > data[last]) {
                nextGreater = i;
                break;
            }
        }
        data = swap(data, nextGreater, last);
        data = reverse(data, last + 1, data.length - 1);
        return true;
    }
    public static int biSearch(int[] dt, int target){
        int left=0, right=dt.length-1;
        int mid=-1;
        while(left<=right){
            mid = (right+left)/2;
            if(dt[mid] == target) return mid;
            if(dt[mid] < target) left=mid+1;
            else right=mid-1;
        }
        return -1;
    }
    public static int biSearchMax(long[] dt, long target){
        int left=-1, right=dt.length;
        int mid=-1;

        while((right-left)>1){
            mid = left + (right-left)/2;
            if(dt[mid] <= target) left=mid;
            else right=mid;
        }
        return left;
    }
    public static int biSearchMaxAL(ArrayList<Integer> dt, long target){
        int left=-1, right=dt.size();
        int mid=-1;

        while((right-left)>1){
            mid = left + (right-left)/2;
            if(dt.get(mid) <= target) left=mid;
            else right=mid;
        }
        return left;
    }
    private static <T>void fill(T[][] ob, T res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}
    private static void fill(boolean[][] ob,boolean res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}
    private static void fill(int[][] ob, int res){      for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}
    private static void fill(long[][] ob, long res){    for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}
    private static void fill(char[][] ob, char res){    for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}
    private static void fill(double[][] ob, double res){for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}
    private static void fill(int[][][] ob,int res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}
    private static void fill(long[][][] ob,long res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}
    private static <T>void fill(T[][][] ob,T res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}
    private static void fill_parent(int[] ob){ for(int i=0; i<ob.length; i++) ob[i]=i; }
    private static boolean same3(long a, long b, long c){
        if(a!=b) return false;
        if(b!=c) return false;
        if(c!=a) return false;
        return true;
    }
    private static boolean dif3(long a, long b, long c){
        if(a==b) return false;
        if(b==c) return false;
        if(c==a) return false;
        return true;
    }
    private static double hypotenuse(double a, double b){
        return Math.sqrt(a*a+b*b);
    }
    private static long factorial(int n) {
        long ans=1;
        for(long i=n; i>0; i--){ ans*=i; }
        return ans;
    }
    private static long facMod(int n, long mod) {
        long ans=1;
        for(long i=n; i>0; i--) ans = (ans * i) % mod;
        return ans;
    }
    private static long lcm(long m, long n){
        long ans = m/gcd(m,n);
        ans *= n;
        return ans;
    }
    private static long gcd(long m, long n) {
        if(m < n) return gcd(n, m);
        if(n == 0) return m;
        return gcd(n, m % n);
    }
    private static boolean isPrime(long a){
        if(a==1) return false;
        for(int i=2; i<=Math.sqrt(a); i++){  if(a%i == 0) return false;  }
        return true;
    }
    static long modInverse(long a, long mod) {
    /* Fermat's little theorem: a^(MOD-1) => 1
    Therefore (divide both sides by a): a^(MOD-2) => a^(-1) */
        return binpowMod(a, mod - 2, mod);
    }
    static long binpowMod(long a, long b, long mod) {
        long res = 1;
        while (b > 0) {
            if (b % 2 == 1) res = (res * a) % mod;
            a = (a * a) % mod;
            b /= 2;
        }
        return res;
    }
    private static int getDigit2(long num){
        long cf = 1;    int d=0;
        while(num >= cf){   d++;    cf = 1<<d;  }
        return d;
    }
    private static int getDigit10(long num){
        long cf = 1;    int d=0;
        while(num >= cf){   d++;    cf*=10;     }
        return d;
    }
    private static boolean isInArea(int y, int x, int h, int w){
        if(y<0) return false;
        if(x<0) return false;
        if(y>=h) return false;
        if(x>=w) return false;
        return true;
    }
    private static ArrayList<Integer> generatePrimes(int n) {
        int[] lp = new int[n + 1];
        ArrayList<Integer> pr = new ArrayList<>();
        for (int i = 2; i <= n; ++i) {
            if (lp[i] == 0) {
                lp[i] = i;
                pr.add(i);
            }
            for (int j = 0; j < pr.size() && pr.get(j) <= lp[i] && i * pr.get(j) <= n; ++j) {
                lp[i * pr.get(j)] = pr.get(j);
            }
        }
        return pr;
    }
    static long nPrMod(int n, int r, long MOD) {
        long res = 1;
        for (int i = (n - r + 1); i <= n; i++) {
            res = (res * i) % MOD;
        }
        return res;
    }
    static long nCr(int n, int r) {
        if (r > (n - r))
            r = n - r;
        long ans = 1;
        for (int i = 1; i <= r; i++) {
            ans *= n;
            ans /= i;
            n--;
        }
        return ans;
    }
    static long nCrMod(int n, int r, long MOD) {
        long rFactorial = nPrMod(r, r, MOD);
        long first = nPrMod(n, r, MOD);
        long second = binpowMod(rFactorial, MOD-2, MOD);
        return  (first * second) % MOD;
    }
    static void printBitRepr(int n) {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < 32; i++) {
            int mask = (1 << i);
            res.append((mask & n) == 0 ? "0" : "1");
        }
        out.println(res);
    }
    static String bitString(int n) {return Integer.toBinaryString(n);}
    static int setKthBitToOne(int n, int k) { return (n | (1 << k)); } // zero indexed
    static int setKthBitToZero(int n, int k) { return (n & ~(1 << k)); }
    static int invertKthBit(int n, int k) { return (n ^ (1 << k)); }
    static boolean isPowerOfTwo(int n) { return (n & (n - 1)) == 0; }
    static HashMap<Character, Integer> counts(String word) {
        HashMap<Character, Integer> counts = new HashMap<>();
        for (int i = 0; i < word.length(); i++) counts.merge(word.charAt(i), 1, Integer::sum);
        return counts;
    }
    static HashMap<Integer, Integer> counts(int[] arr) {
        HashMap<Integer, Integer> counts = new HashMap<>();
        for (int value : arr) counts.merge(value, 1, Integer::sum);
        return counts;
    }
    static HashMap<Long, Integer> counts(long[] arr) {
        HashMap<Long, Integer> counts = new HashMap<>();
        for (long l : arr) counts.merge(l, 1, Integer::sum);
        return counts;
    }
    static HashMap<Character, Integer> counts(char[] arr) {
        HashMap<Character, Integer> counts = new HashMap<>();
        for (char c : arr) counts.merge(c, 1, Integer::sum);
        return counts;
    }
    static long hash(int x, int y) {
        return x* 1_000_000_000L +y;
    }
    static final Random random = new Random();
    static void sort(int[] a) {
        int n = a.length;// shuffle, then sort
        for (int i = 0; i < n; i++) {
            int oi = random.nextInt(n), temp = a[oi];
            a[oi] = a[i];
            a[i] = temp;
        }
        Arrays.sort(a);
    }
    static void sort(long[] arr) {
        shuffleArray(arr);
        Arrays.sort(arr);
    }
    static void shuffleArray(long[] arr) {
        int n = arr.length;
        for(int i=0; i<n; ++i){
            long tmp = arr[i];
            int randomPos = i + random.nextInt(n-i);
            arr[i] = arr[randomPos];
            arr[randomPos] = tmp;
        }
    }
}
static class Tuple implements Comparable<Tuple> {
    int a;
    int b;
    int c;
    public Tuple(int a, int b) {
        this.a = a;
        this.b = b;
        this.c = 0;
    }
    public Tuple(int a, int b, int c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }
    public int getA() { return a; }
    public int getB() { return b; }
    public int getC() { return c; }
    public int compareTo(Tuple other) {
        if (this.a == other.a) {
            if (this.b == other.b) return Long.compare(this.c, other.c);
            return Long.compare(this.b, other.b);
        }
        return Long.compare(this.a, other.a);
    }
    @Override
    public int hashCode() { return Arrays.deepHashCode(new Integer[]{a, b, c}); }
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Tuple)) return false;
        Tuple pairo = (Tuple) o;
        return (this.a == pairo.a && this.b == pairo.b && this.c == pairo.c);
    }
    @Override
    public String toString() { return String.format("(%d %d %d)  ", this.a, this.b, this.c); }
}
private static int abs(int a){  return (a>=0) ? a: -a;  }
private static int min(int... ins){ int min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }
private static int max(int... ins){ int max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }
private static int sum(int... ins){ int total = 0; for (int v : ins) { total += v; } return total; }
private static long abs(long a){    return (a>=0) ? a: -a;  }
private static long min(long... ins){ long min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }
private static long max(long... ins){ long max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }
private static long sum(long... ins){ long total = 0; for (long v : ins) { total += v; } return total; }
private static double abs(double a){    return (a>=0) ? a: -a;  }
private static double min(double... ins){ double min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }
private static double max(double... ins){ double max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }
private static double sum(double... ins){ double total = 0; for (double v : ins) { total += v; } return total; }

}

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main
{
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
    static class Pair implements Comparable<Pair> {
        int x,y;
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
        public int compareTo(Pair o) {
            if(x!=o.x)
                return x-o.x;
            return this.y - o.y;
        }
        public int hashCode() {
            return (int)(1L*1000000000*x + y)%1000000007;
        }
        public boolean equals(Object o) {
            if(o instanceof Pair) {
                Pair other = (Pair)o;
                return other.hashCode()==this.hashCode();
            }
            else return false;
        }
        public String toString(){
            return x+" "+y;
        }
    }
    //static Scanner sc = new Scanner(System.in);
    static Reader sc = new Reader();
    static StringBuilder sb = new StringBuilder();
    static PrintWriter pw = new PrintWriter(System.out,true);
    static TreeSet<Integer> offer_at[];
    static Pair offer[];
    static int arr[],n,m;
    public static void main(String[] args) throws IOException {
        //Code start from here
        n = sc.nextInt();m = sc.nextInt();
        arr= new int[n];
        for(int i =0;i<n;i++)
            arr[i]= sc.nextInt();
        offer= new Pair[m];
        offer_at= new TreeSet[n];
        for(int i=0;i<n;i++)
            offer_at[i]=new TreeSet<>();
        for(int i =0;i<m;i++) {
            int day = sc.nextInt(),type = sc.nextInt()-1;
            offer[i]=new Pair(day,type);
            offer_at[offer[i].y].add(day);
        }
        Arrays.sort(offer);
        int lo=0,hi=4000000,mid;
        while(lo<hi) {
            mid = (lo+hi)>>1;
            if(check(mid)) {
                if(!check(mid-1)) {
                    lo=mid;
                    break;
                }else hi = mid-1;
            } else lo = mid+1;
        }
        sb.append(lo);
        pw.println(sb);
        pw.flush();
        pw.close();
    }
    static boolean check(int D) {
        int cur=0,prev =0;
        int arrr[]= new int[n];
        for(int i =0;i<n;i++)
            arrr[i]= arr[i];

        for(int i =0;i<m;i++){
            if(offer[i].x>D)
                break;
            cur+=offer[i].x - prev;
            prev = offer[i].x;
            if(offer[i].x==offer_at[offer[i].y].lower(D+1)) {
                int liya = min (cur,arrr[offer[i].y]);
                arrr[offer[i].y]-=liya;
                cur-=liya;
            }
        }
        cur+= D-prev;
        int left = 0;
        for(int i =0;i<n;i++){
            left+=arrr[i];
        }

        return cur>=2*left;
    }
}

import java.io.*;
import java.util.*;

public class Main {
    // static ArrayList a[]=new ArrayList[3000001];
     static boolean prime[]=new boolean [3000001];
     static int a[];
     static pair p[];
     static int sum=0;
     static boolean cheak(int n) {
    	 int have=0;
    	 int at=n;
    	 int get=0;
    	 TreeSet<Integer>tr=new TreeSet<>();
    	 for(int i=0;i<p.length && at>0;i++) {
    		 pair q=p[i];
    		 if(q.x>n)
    			 continue;
    		 if(at>q.x) {
    			 have+=(at-q.x);
    			 at=q.x;
    		 }
    		 if(!tr.contains(q.y)) {
    			 int take=a[q.y];
    			 int can=Math.min(take, at);
    			 at-=can;
    			 get+=can;
    			 tr.add(q.y);
    		 }
    	 }
         have+=at;
    	 get+=have/2;
    	 return (get>=sum);

     }
     public static void main(String[]args)
    {
        InputReader in=new InputReader(System.in);
        PrintWriter pw = new PrintWriter(System.out);
        int n=in.nextInt();
        int m=in.nextInt();
        a=new int[n+1];
        p=new pair[m];
        for(int i=1;i<=n;i++) {
        	a[i]=in.nextInt();
        	sum+=a[i];
        }
        for(int i=0;i<m;i++) {
        	int x=in.nextInt();
        	int y=in.nextInt();
        	p[i]=new pair(x,y);
        }
        Arrays.sort(p,new Comparator<pair>() {
        	public int compare(pair p1,pair p2) {
        		if(p1.x>p2.x) return -1;
        		if(p1.x<p2.x) return 1;
        		return 0;
        	}
        });
        int start=1;
        int end=2*sum;
        int ans=-1;
        while(start<=end) {
        	int mid=(start+end)/2;
        	if(cheak(mid)) {
        		ans=mid;
        		end=mid-1;
        	}
        	else
        		start=mid+1;
        }
        pw.println(ans);
        pw.flush();
        pw.close();

    }
    private static void debug(Object... o) {
        System.out.println(Arrays.deepToString(o));
    }
   static class InputReader
        {
        private final InputStream stream;
        private final byte[] buf = new byte[8192];
        private int curChar, snumChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream)
        {
            this.stream = stream;
        }
        public int snext()
        {
            if (snumChars == -1)
                throw new InputMismatchException();
            if (curChar >= snumChars)
            {
                curChar = 0;
                try
                {
                    snumChars = stream.read(buf);
                }

                catch (IOException e)
                {
                    throw new InputMismatchException();
                }

                if (snumChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt()
        {
            int c = snext();
            while (isSpaceChar(c))
            {
                c = snext();
            }
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = snext();
            }
            int res = 0;
            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = snext();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public long nextLong()
        {
            int c = snext();
            while (isSpaceChar(c))
            {
                c = snext();
            }
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = snext();
            }
            long res = 0;
            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = snext();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int[] nextIntArray(int n)
        {
            int a[] = new int[n];
            for (int i = 0; i < n; i++)
            {
                a[i] = nextInt();
            }
            return a;
        }
        static class tri implements Comparable<tri> {
            int p, c, l;

            tri(int p, int c, int l) {
                this.p = p;
                this.c = c;
                this.l = l;
            }

            public int compareTo(tri o) {
                return Integer.compare(l, o.l);
            }
        }

        public String readString()
        {
            int c = snext();
            while (isSpaceChar(c))
            {
                c = snext();
            }
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = snext();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public String nextLine()
        {
            int c = snext();
            while (isSpaceChar(c))
                c = snext();
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = snext();
            } while (!isEndOfLine(c));
            return res.toString();
        }

        public boolean isSpaceChar(int c)
        {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private boolean isEndOfLine(int c)
        {
            return c == '\n' || c == '\r' || c == -1;
        }

        public interface SpaceCharFilter
        {
            public boolean isSpaceChar(int ch);
        }
    }
   public static long modularExponentiation(long x,long n,long M)
   {
       long result=1;
       while(n>0)
       {
           if(n % 2 ==1)
               result=(result%M * x%M)%M;
           x=(x%M * x%M)%M;
           n=n/2;
       }
       return result;
   }

   public static long modInverse(int A,int M)
   {
       return modularExponentiation(A,M-2,M);
   }

   public static long modInverse(long A,long M)
   {
       return modularExponentiation(A,M-2,M);
   }
   static class pair implements Comparable<pair>
   {
       Integer x, y;
       pair(int x,int y)
       {
           this.x=x;
           this.y=y;
       }

       public int compareTo(pair o) {
           int result = x.compareTo(o.x);
           if(result==0)
               result = y.compareTo(o.y);

           return result;
       }

       public String toString()
       {
           return x+" "+y;
       }

       public boolean equals(Object o)
       {
           if (o instanceof pair)
          {
               pair p = (pair)o;
               return (Math.abs(p.x-x)==0 && Math.abs(p.y-y)==0);
           }
           return false;
       }

       public int hashCode()
       {
           return new Long(x).hashCode()*31 + new Long(y).hashCode();
       }
   }
    public static long GCD(long a,long b)
    {
        if(b==0)
            return a;
        else
            return GCD(b,a%b);
    }
    public static long[] shuffle(long[] a, Random gen){
        for(int i = 0, n = a.length;i < n;i++){
            int ind = gen.nextInt(n-i)+i;
            long d = a[i];
            a[i] = a[ind];
            a[ind] = d;
        }
        return a;
    }

}

import java.util.*;
import java.io.*;
import java.text.*;
public class Main{
    //SOLUTION BEGIN
    //This code is not meant for understanding, you have been warned.
    void pre() throws Exception{}
    void solve(int TC) throws Exception{
        int n = ni(), m = ni();
        long[] count = new long[n];
        for(int i = 0; i< n; i++)count[i] = ni();
        HashSet<Integer>[] offer = new HashSet[MX];TreeSet<Integer>[] roffer = new TreeSet[MX];
        for(int i = 0; i< MX; i++){offer[i] = new HashSet<>();roffer[i] = new TreeSet<>();}
        for(int i = 0; i< m; i++){
            int d = ni(), t = ni()-1;
            offer[d].add(t);
            roffer[t].add(d);
        }
        int lo = 0, hi = MX;
        while(lo+1<hi){
            int mid = lo+(hi-lo)/2;
            if(check(count, offer, roffer, mid))hi = mid;
            else lo = mid;
        }
        if(check(count,offer, roffer,lo))hi = lo;
        pn(hi);
    }
    boolean check(long[] cnt, HashSet<Integer>[] offer, TreeSet<Integer>[] roffer, int day){
        long[] count = Arrays.copyOfRange(cnt, 0, cnt.length);
        long coin = 0, rem = 0;
        for(int cur = 1; cur<= day; cur++){
            coin++;
            for(int x:offer[cur]){
                if(roffer[x].floor(day)!=cur)continue;
                long mn = Math.min(coin, count[x]);
                count[x] -= mn;
                coin-=mn;
            }
        }
        for(long i:count)rem+=2*i;
        return coin>=rem;
    }
    //SOLUTION END
    void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
    long mod = (long)998244353, IINF = (long)1e18;
    final int INF = (int)1e9, MX = (int)5e5+1;
    DecimalFormat df = new DecimalFormat("0.00000000000");
    double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8;
    static boolean multipleTC = false, memory = false;
    FastReader in;PrintWriter out;
    void run() throws Exception{
        in = new FastReader();
        out = new PrintWriter(System.out);
        //Solution Credits: Taranpreet Singh
        int T = (multipleTC)?ni():1;
        pre();for(int t = 1; t<= T; t++)solve(t);
        out.flush();
        out.close();
    }
    public static void main(String[] args) throws Exception{
        if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
        else new Main().run();
    }
    long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
    int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
    int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
    void p(Object o){out.print(o);}
    void pn(Object o){out.println(o);}
    void pni(Object o){out.println(o);out.flush();}
    String n()throws Exception{return in.next();}
    String nln()throws Exception{return in.nextLine();}
    int ni()throws Exception{return Integer.parseInt(in.next());}
    long nl()throws Exception{return Long.parseLong(in.next());}
    double nd()throws Exception{return Double.parseDouble(in.next());}

    class FastReader{
        BufferedReader br;
        StringTokenizer st;
        public FastReader(){
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public FastReader(String s) throws Exception{
            br = new BufferedReader(new FileReader(s));
        }

        String next() throws Exception{
            while (st == null || !st.hasMoreElements()){
                try{
                    st = new StringTokenizer(br.readLine());
                }catch (IOException  e){
                    throw new Exception(e.toString());
                }
            }
            return st.nextToken();
        }

        String nextLine() throws Exception{
            String str = "";
            try{
                str = br.readLine();
            }catch (IOException e){
                throw new Exception(e.toString());
            }
            return str;
        }
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Collections;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author beginner1010
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskF2 solver = new TaskF2();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskF2 {
        boolean can(int days, ArrayList<Sale> allSales, int[] required) {
            ArrayList<Sale> sales = new ArrayList<>();
            boolean[] seenType = new boolean[required.length];
            for (int i = allSales.size() - 1; i >= 0; i--) {
                if (seenType[allSales.get(i).type] || allSales.get(i).day > days)
                    continue;
                seenType[allSales.get(i).type] = true;
                sales.add(new Sale(allSales.get(i).day, allSales.get(i).type));
            }

            Collections.reverse(sales);
            int sum = 0;
            for (int i = 0; i < required.length; i++) {
                sum += required[i];
            }

            int burles = 0;
            int lastDay = 0;
            for (int i = 0; i < sales.size(); i++) {
                int day = sales.get(i).day;
                int type = sales.get(i).type;
                burles += day - lastDay;
                int discount = Math.min(required[type], burles);
                burles -= discount;
                sum -= discount;
                lastDay = sales.get(i).day;
            }
            burles += days - lastDay;
            return sum * 2 <= burles;
        }

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            int[] required = new int[n];
            for (int i = 0; i < n; i++) {
                required[i] = in.nextInt();
            }

            ArrayList<Sale> allSales = new ArrayList<>();
            for (int i = 0; i < m; i++) {
                int day = in.nextInt();
                int type = in.nextInt() - 1;
                allSales.add(new Sale(day, type));
            }
            Collections.sort(allSales);

            int lo = 0;
            int hi = (int) (4e5 + 5);
            while (lo < hi) {
                int mid = (lo + hi) >> 1;
                if (can(mid, allSales, required) == true) {
                    hi = mid;
                } else {
                    lo = mid + 1;
                }
            }
            out.println(lo);
        }

        class Sale implements Comparable<Sale> {
            int day;
            int type;

            Sale(int day, int type) {
                this.day = day;
                this.type = type;
            }

            public int compareTo(Sale o) {
                if (this.day != o.day) return this.day < o.day ? -1 : 1;
                if (this.type != o.type) return this.type < o.type ? -1 : 1;
                return 0;
            }

        }

    }

    static class InputReader {
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputStream stream;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        private boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isWhitespace(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isWhitespace(c));
            return res * sgn;
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Comparator;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Jeel Vaishnav
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
        solver.solve(1, in, out);
        out.close();
    }

    static class F2MicrotransactionsHardVersion {
        public void solve(int testNumber, InputReader sc, PrintWriter out) {
            int n = sc.nextInt();
            int m = sc.nextInt();

            long totcnt = 0;

            long k[] = new long[n];
            for (int i = 0; i < n; ++i) {
                k[i] = sc.nextLong();
                totcnt += k[i];
            }

            Pair p[] = new Pair[m];
            for (int i = 0; i < m; ++i) {
                p[i] = new Pair(sc.nextInt(), sc.nextInt() - 1);
            }

            Arrays.sort(p, new Comparator<Pair>() {

                public int compare(Pair o1, Pair o2) {
                    return o2.day - o1.day;
                }
            });

            long start = 0, end = (long) 1e11, ans = (long) 1e11;
            while (start <= end) {
                long mid = (start + end) >> 1;

                long req[] = new long[n];
                for (int i = 0; i < n; ++i)
                    req[i] = k[i];

                long alr = 0;
                int lastDay = (int) (Math.min((long) 2e5, mid));

                for (int i = 0; i < m; ++i) {
                    if (p[i].day > mid)
                        continue;

                    if (lastDay > p[i].day)
                        lastDay = p[i].day;

                    while (lastDay > 0 && req[p[i].type] > 0) {
                        req[p[i].type]--;
                        lastDay--;
                        alr++;
                    }
                }

                long reqDays = 2 * totcnt - alr;
                if (reqDays <= mid) {
                    ans = mid;
                    end = mid - 1;
                } else {
                    start = mid + 1;
                }
            }

            out.print(ans);
        }

        class Pair {
            int day;
            int type;

            Pair(int a, int b) {
                day = a;
                type = b;
            }

        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();

            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }

                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();

            while (isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

import java.io.*;
import java.math.BigInteger;
import java.util.*;

public class test {
	public static void main(String[] args) throws IOException {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		PrintWriter out = new PrintWriter(outputStream);
		InputReader in = new InputReader(inputStream);

//		for(int i=4;i<=4;i++) {
//			InputStream uinputStream = new FileInputStream("leftout.in");
//			String f = i+".in";
//			InputStream uinputStream = new FileInputStream(f);
//			InputReader in = new InputReader(uinputStream);
//			PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("leftout.out")));
			Task t = new Task();
			t.solve(in, out);
			out.close();
//		}
	}

	static class Task {

		public void solve(InputReader in, PrintWriter out) throws IOException {
//			Dumper.print(Long.MAX_VALUE);
//			int n = in.nextInt();
//			long a[] = new long[n];
//			for(int i=0;i<n;i++) {
//				a[i] = in.nextLong();
//			}
//			pair c[] = new pair[n];
//			for(int i=0;i<n;i++) {
//				a[i] *= (i+1)*(n-i);
//				c[i] = new pair(-1*a[i],i);
//			}
//			Arrays.sort(c);
//
//			long b[] = new long[n];
//			long d[] = new long[n];
//			for(int i=0;i<n;i++) {
//				d[i] = in.nextLong();
//			}
//			ArrayUtils.sort(d);
//			for(int i=0;i<n;i++) {
//				b[c[i].idx] = d[i];
//			}
//			long f = 998244353;
//			long ret[] = new long[n];
//			for(int i=n-1;i>=0;i--) {
//				ret[i]=a[i];
//				ret[i]%=f;
//				ret[i]*=b[i];
//				ret[i]%=f;
//			}
//			long v = 0;
//			for(long tmp:ret) {
//				v+=tmp;
//				v%=f;
//			}
//			out.println(v);
			int n = in.nextInt();
			int m = in.nextInt();
			int s = 0;
			int need[] = new int[n+1];
			for(int i=1;i<=n;i++) {
				need[i] = in.nextInt();
				s+=need[i];
			}
			Set<Integer>[] g = new HashSet[1001];
			for(int i=1;i<1001;i++) g[i] = new HashSet<Integer>();
			for(int i=0;i<m;i++) {
				int d = in.nextInt();
				int t = in.nextInt();
				g[d].add(t);
			}

			int l = 1;
			int r = 2002;
			while(l<r-1) {
				int mid = l+(r-l)/2;
				if(is_ok(g,mid,need,s)) {
					r=mid;
				}else {
					l=mid;
				}
			}
			if(is_ok(g,l,need,s)) out.println(l);
			else out.println(r);
		}
		boolean is_ok(Set<Integer>[] g, int mid, int need[], int all) {
			int offer[] = new int[need.length];
			for(int i=1;i<=Math.min(mid, g.length-1);i++) {
				for(int j:g[i]) offer[j] = i;
			}
			ArrayList<offer> arr = new ArrayList<offer>();
			for(int i=1;i<offer.length;i++) {
				if(offer[i]!=0) arr.add(new offer(i,offer[i]));
			}
			Collections.sort(arr);
			int temp[] = need.clone();
			if(arr.size()==0) return mid>=2*all;
			int cur = 0; int p=0;
			for(int i=1;i<=mid;i++) {
				cur++;
				while(p<arr.size()&&i==arr.get(p).day) {
					int item = arr.get(p).item;
					int num = temp[item];
					if(cur>=num) {
						cur-=num;
						all-=num;
						temp[item]=0;
					}else if(cur<num) {
						temp[item]-=cur;
						all-=cur;
						cur=0;
					}
					p++;
				}
			}
			return cur>=2*all;
		}
		class offer implements Comparable<offer>{
			int item; int day;
			public offer(int a, int b) {
				item = a; day=b;
			}
			@Override
			public int compareTo(offer t) {
				return this.day-t.day;
			}
		}
		class pair implements Comparable<pair>{
			Long val; int idx;
			public pair(long a, int b) {
				val=a;idx=b;
			}
			@Override
			public int compareTo(pair t) {
				return this.val.compareTo(t.val);
			}
		}
		boolean is_prime(int a) {
			if(a==2||a==3) return true;
			for(int i=2;i<=Math.sqrt(a);i++) {
				if(a%i==0) return false;
			}
			return true;
		}

		class TreeNode {
			int val;
			TreeNode left;
			TreeNode right;
			TreeNode(int x) { val = x; }
		}

		public int GCD(int a, int b) {
		   if (b==0) return a;
		   return GCD(b,a%b);
		}
	}

    static class ArrayUtils {
        static final long seed = System.nanoTime();
        static final Random rand = new Random(seed);

        public static void sort(int[] a) {
            shuffle(a);
            Arrays.sort(a);
        }

        public static void shuffle(int[] a) {
            for (int i = 0; i < a.length; i++) {
                int j = rand.nextInt(i + 1);
                int t = a[i];
                a[i] = a[j];
                a[j] = t;
            }
        }

        public static void sort(long[] a) {
            shuffle(a);
            Arrays.sort(a);
        }

        public static void shuffle(long[] a) {
            for (int i = 0; i < a.length; i++) {
                int j = rand.nextInt(i + 1);
                long t = a[i];
                a[i] = a[j];
                a[j] = t;
            }
        }

    }
	static class BIT{
		int arr[];
		int n;
		public BIT(int a) {
			n=a;
			arr = new int[n];
		}
		int sum(int p) {
			int s=0;
			while(p>0) {
				s+=arr[p];
				p-=p&(-p);
			}
			return s;
		}
		void add(int p, int v) {
			while(p<n) {
				arr[p]+=v;
				p+=p&(-p);
			}
		}
	}
	static class DSU{
		int[] arr;
		int[] sz;
		public DSU(int n) {
			arr = new int[n];
			sz = new int[n];
			for(int i=0;i<n;i++) arr[i] = i;
			Arrays.fill(sz, 1);
		}
		public int find(int a) {
			if(arr[a]!=a) arr[a] = find(arr[a]);
			return arr[a];
		}
		public void union(int a, int b) {
			int x = find(a);
			int y = find(b);
			if(x==y) return;
			arr[x] = y;
			sz[y] += sz[x];
		}
		public int size(int x) {
			return sz[find(x)];
		}
	}
	static class MinHeap<Key> implements Iterable<Key> {
		private int maxN;
		private int n;
		private int[] pq;
		private int[] qp;
		private Key[] keys;
		private Comparator<Key> comparator;

		public MinHeap(int capacity){
			if (capacity < 0) throw new IllegalArgumentException();
			this.maxN = capacity;
			n=0;
			pq = new int[maxN+1];
			qp = new int[maxN+1];
			keys = (Key[]) new Object[capacity+1];
			Arrays.fill(qp, -1);
		}

		public MinHeap(int capacity, Comparator<Key> c){
			if (capacity < 0) throw new IllegalArgumentException();
			this.maxN = capacity;
			n=0;
			pq = new int[maxN+1];
			qp = new int[maxN+1];
			keys = (Key[]) new Object[capacity+1];
			Arrays.fill(qp, -1);
			comparator = c;
		}
		public boolean isEmpty()	{ return n==0; 	}
		public int size()			{ return n;		}
		public boolean contains(int i) {
	        if (i < 0 || i >= maxN) throw new IllegalArgumentException();
	        return qp[i] != -1;
		}
		public int peekIdx() {
	        if (n == 0) throw new NoSuchElementException("Priority queue underflow");
	        return pq[1];
		}
		public Key peek(){
			if(isEmpty()) throw new NoSuchElementException("Priority queue underflow");
			return keys[pq[1]];
		}
		public int poll(){
			if(isEmpty()) throw new NoSuchElementException("Priority queue underflow");
			int min = pq[1];
			exch(1,n--);
			down(1);
			assert min==pq[n+1];
			qp[min] = -1;
			keys[min] = null;
			pq[n+1] = -1;
			return min;
		}
	    public void update(int i, Key key) {
	        if (i < 0 || i >= maxN) throw new IllegalArgumentException();
	        if (!contains(i)) {
	        	this.add(i, key);
	        }else {
	        	keys[i] = key;
	        	up(qp[i]);
	        	down(qp[i]);
	        }
	    }
		private void add(int i, Key x){
	        if (i < 0 || i >= maxN) throw new IllegalArgumentException();
	        if (contains(i)) throw new IllegalArgumentException("index is already in the priority queue");
	        n++;
	        qp[i] = n;
	        pq[n] = i;
	        keys[i] = x;
	        up(n);
		}
		private void up(int k){
			while(k>1&&less(k,k/2)){
				exch(k,k/2);
				k/=2;
			}
		}
		private void down(int k){
			while(2*k<=n){
				int j=2*k;
				if(j<n&&less(j+1,j)) j++;
				if(less(k,j)) break;
				exch(k,j);
				k=j;
			}
		}

		public boolean less(int i, int j){
	        if (comparator == null) {
	            return ((Comparable<Key>) keys[pq[i]]).compareTo(keys[pq[j]]) < 0;
	        }
	        else {
	            return comparator.compare(keys[pq[i]], keys[pq[j]]) < 0;
	        }
		}

		public void exch(int i, int j){
	        int swap = pq[i];
	        pq[i] = pq[j];
	        pq[j] = swap;
	        qp[pq[i]] = i;
	        qp[pq[j]] = j;
		}

		@Override
		public Iterator<Key> iterator() {
			// TODO Auto-generated method stub
			return null;
		}
	}

    private static class InputReader
    {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int zcurChar;
        private int znumChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream)
        {
            this.stream = stream;
        }

        public int read()
        {
            if (znumChars == -1)
                throw new InputMismatchException();
            if (zcurChar >= znumChars)
            {
            	zcurChar = 0;
                try
                {
                    znumChars = stream.read(buf);
                } catch (IOException e)
                {
                    throw new InputMismatchException();
                }
                if (znumChars <= 0)
                    return -1;
            }
            return buf[zcurChar++];
        }

        public int nextInt()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public String nextString()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public double nextDouble()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.')
            {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.')
            {
                c = read();
                double m = 1;
                while (!isSpaceChar(c))
                {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public long nextLong()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c)
        {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next()
        {
            return nextString();
        }

        public interface SpaceCharFilter
        {
            public boolean isSpaceChar(int ch);
        }
        public int[] readIntArray(int n) {
            int[] ret = new int[n];
            for (int i = 0; i < n; i++) {
                ret[i] = nextInt();
            }
            return ret;
        }
    }

	static class Dumper {
		static void print_int_arr(int[] arr) {
			for (int i = 0; i < arr.length; i++) {
				System.out.print(arr[i] + " ");
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print_char_arr(char[] arr) {
			for (int i = 0; i < arr.length; i++) {
				System.out.print(arr[i] + " ");
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print_double_arr(double[] arr) {
			for (int i = 0; i < arr.length; i++) {
				System.out.print(arr[i] + " ");
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print_2d_arr(int[][] arr, int x, int y) {
			for (int i = 0; i < x; i++) {
				for (int j = 0; j < y; j++) {
					System.out.print(arr[i][j] + " ");
				}
				System.out.println();
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print_2d_arr(boolean[][] arr, int x, int y) {
			for (int i = 0; i < x; i++) {
				for (int j = 0; j < y; j++) {
					System.out.print(arr[i][j] + " ");
				}
				System.out.println();
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print(Object o) {
			System.out.println(o.toString());
		}

		static void getc() {
			System.out.println("here");
		}
	}
}

import sun.reflect.generics.tree.Tree;

import java.io.*;
import java.util.*;

public class Task {

    public static void main(String[] args) throws IOException {

        new Task().go();
    }

    PrintWriter out;
    Reader in;
    BufferedReader br;

    Task() throws IOException {

        try {

            //br = new BufferedReader( new FileReader("input.txt") );
            in = new Reader("input.txt");
            out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) );
        }
        catch (Exception e) {

            //br = new BufferedReader( new InputStreamReader( System.in ) );
            in = new Reader();
            out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
        }
    }

    void go() throws IOException {

        int t = 1;
        while (t > 0) {
            solve();
            //out.println();
            t--;
        }

        out.flush();
        out.close();
    }

    int inf = 2000000000;
    int mod = 1000000007;
    double eps = 0.000000001;

    int n;
    int m;
    ArrayList<Integer>[] g;
    void solve() throws IOException {

        int n = in.nextInt();
        int m = in.nextInt();
        int[] a = in.nextIntArray(n);

        g = new ArrayList[1010];
        for (int i = 0; i < g.length; i++)
            g[i] = new ArrayList<>();

        for (int i = 0; i < m; i++) {
            int x = in.nextInt();
            int y = in.nextInt();
            g[x].add(y - 1);
        }

        int l = 0;
        int r = 10000000;

        while (r > l) {
            int mid = (l + r) / 2;
            int[] b = new int[n];
            int sum = 0;

            int[] last = new int[n];

            for ( int i = 1; i <= mid; i++) {
                if (i < g.length)
                    for (int t : g[i]) {
                        last[t] = i;
                    }
            }

            for ( int i = 1; i <= mid; i++) {
                sum++;
                if (i < g.length)
                    for (int t : g[i]) {
                        if (last[t] == i) {
                            while (b[t] < a[t] && sum > 0) {
                                b[t]++;
                                sum--;
                            }
                        }
                    }
            }

            //System.err.println(mid + " " + sum);

            for (int i = 0; i < n; i++)
                sum -= 2 * (a[i] - b[i]);

            if (sum < 0)
                l = mid + 1;
            else
                r = mid;
        }

        out.print(r);
    }

    class Pair implements Comparable<Pair> {
        int a;
        int b;

        Pair(int a, int b) {
            this.a = a;
            this.b = b;
        }

        public int compareTo(Pair p) {
            if (a != p.a)
                return Integer.compare(a, p.a);
            else
                return Integer.compare(b, p.b);
        }
    }

    class Item {

        int a;
        int b;
        int c;

        Item(int a, int b, int c) {
            this.a = a;
            this.b = b;
            this.c = c;
        }

    }

    class Reader {

        BufferedReader  br;
        StringTokenizer tok;

        Reader(String file) throws IOException {
            br = new BufferedReader( new FileReader(file) );
        }

        Reader() throws IOException {
            br = new BufferedReader( new InputStreamReader(System.in) );
        }

        String next() throws IOException {

            while (tok == null || !tok.hasMoreElements())
                tok = new StringTokenizer(br.readLine());
            return tok.nextToken();
        }

        int nextInt() throws NumberFormatException, IOException {
            return Integer.valueOf(next());
        }

        long nextLong() throws NumberFormatException, IOException {
            return Long.valueOf(next());
        }

        double nextDouble() throws NumberFormatException, IOException {
            return Double.valueOf(next());
        }

        String nextLine() throws IOException {
            return br.readLine();
        }

        int[] nextIntArray(int n) throws IOException {
            int[] a = new int[n];
            for (int i = 0; i < n; i++)
                a[i] = nextInt();
            return a;
        }

        ArrayList<Integer>[] nextGraph(int n, int m) throws IOException {
            ArrayList<Integer>[] g = new ArrayList[n];
            for (int i = 0; i < n; i++)
                g[i] = new ArrayList<>();
            for (int i = 0; i < m; i++) {
                int x = nextInt() - 1;
                int y = nextInt() - 1;
                g[x].add(y);
                g[y].add(x);
            }

            return g;
        }

    }

}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;
import java.util.Map;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        Task1165F solver = new Task1165F();
        solver.solve(1, in, out);
        out.close();
    }

    static class Task1165F {
        ArrayList<Pair<Integer, Integer>> al = new ArrayList<>();

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            int arr[] = new int[n];
            int i, j, sum = 0;

            for (i = 0; i < n; i++) {
                arr[i] = in.nextInt();
                sum += arr[i];
            }

            for (i = 0; i < m; i++) {
                int d = in.nextInt();
                int t = in.nextInt() - 1;
                al.add(new Pair(d, t));
            }

            for (i = sum; i <= 2 * sum; i++) {
                int cur = check(arr, n, i, sum);
                // out.println(i + " " + cur);
                if (cur == 0)
                    break;
            }

            out.println(i);

        }

        int check(int arra[], int n, int total_money, int suma) {
            int arr[] = Arrays.copyOf(arra, n);
            int sum = suma;
            int day[] = new int[n];

            int i, j;
            for (Pair t : al) {
                int first = (int) t.getFirst();
                int second = (int) t.getSecond();
                if (first > total_money)
                    continue;
                day[second] = Math.max(day[second], first);
            }

            TreeMap<Integer, Integer> tm = new TreeMap<>();
            for (i = 0; i < n; i++) {
                if (day[i] != 0) {
                    tm.put(day[i], tm.getOrDefault(day[i], 0) + arr[i]);
                }
            }
            //System.out.println(total_money +" " +tm);
            int cur_money = 0;
            for (i = 1; i <= total_money; i++) {
                cur_money++;
                int val = Math.min(tm.getOrDefault(i, 0), cur_money);
                cur_money -= val;
                sum -= val;
            }

            cur_money /= 2;
            sum -= cur_money;
            sum = Math.max(0, sum);
            return sum;
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void println(int i) {
            writer.println(i);
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class Pair<A, B> {
        A first;
        B second;

        public Pair(A first, B second) {
            super();
            this.first = first;
            this.second = second;
        }

        public int hashCode() {
            int hashFirst = first != null ? first.hashCode() : 0;
            int hashSecond = second != null ? second.hashCode() : 0;

            return (hashFirst + hashSecond) * hashSecond + hashFirst;
        }

        public boolean equals(Object other) {
            if (other instanceof Pair) {
                Pair otherPair = (Pair) other;
                return
                        ((this.first == otherPair.first ||
                                (this.first != null && otherPair.first != null &&
                                        this.first.equals(otherPair.first))) &&
                                (this.second == otherPair.second ||
                                        (this.second != null && otherPair.second != null &&
                                                this.second.equals(otherPair.second))));
            }

            return false;
        }

        public String toString() {
            return "(" + first + ", " + second + ")";
        }

        public A getFirst() {
            return first;
        }

        public B getSecond() {
            return second;
        }

    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;

public class Solution {

	private static FastReader in;
	private static PrintStream out;
	private static int n, m;
	private static int[] k;
	private static List<Integer>[] o;
	private static int[][] lasto;
	private final static int MAX = 2000;
	private static int total;

	public static void main(String[] args) {
		in = new FastReader();
		out = System.out;
		solve();
	}

	protected static void solve() {
		n = in.nextInt();
		m = in.nextInt();
		k = new int[n + 1];
		total = 0;
		for (int i = 0; i < n; i++) {
			k[i] = in.nextInt();
			total += k[i];
		}
		o = new ArrayList[MAX + 1];
		lasto = new int[n + 2][2 * MAX + 2];
		for (int i = 0; i < o.length; i++)
			o[i] = new ArrayList<Integer>();
		for (int i = 0; i < m; i++) {
			int day = in.nextInt();
			int product = in.nextInt() - 1;
			o[day].add(product);
			lasto[product][day] = day;
		}
		int ret = solveLine();
		out.printf(Locale.ENGLISH, "%d%n", ret);
	}

	private static int solveLine() {
		for (int product = 0; product < n; product++) {
			int last = 0;
			for (int day = 0; day < lasto[0].length; day++) {
				if (lasto[product][day] == 0)
					lasto[product][day] = last;
				else
					last = lasto[product][day];
			}
		}

		for (int day = 2 * total; day >= 1; day--) {
			int pending = 0;
			int[] cost = new int[2 * total + 2];
			for (int product = 0; product < n; product++) {
				pending += k[product] * 2;
				if (lasto[product][day] != 0) {
					pending -= k[product];
					cost[lasto[product][day]] += k[product];
				}
			}
			if (day < pending) return day + 1;
			int money = 0;
			pending = 2 * total;
			for (int i = 1; i <= day; i++ ) {
				money++;
				if (cost[i] > 0) {
					if (cost[i] > money) cost[i] = money;
						pending -= (2 * cost[i]);
						money -= cost[i];
				}
			}
			if (money < pending) return day + 1;
		}
//		throw new RuntimeException();
		return 1;
	}

	protected static class FastReader {
		BufferedReader br;
		StringTokenizer st;

		public FastReader() {
			this(System.in);
		}

		public FastReader(InputStream in) {
			this(new InputStreamReader(in));
		}

		public FastReader(InputStreamReader in) {
			br = new BufferedReader((in));
		}

		String next() {
			while (st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return str;
		}
	}

}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.stream.IntStream;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in Actual solution is at the top
 *
 * @author NMouad21
 */
public class Main {

  public static void main(String[] args) {
    InputStream inputStream = System.in;
    OutputStream outputStream = System.out;
    InputReader in = new InputReader(inputStream);
    PrintWriter out = new PrintWriter(outputStream);
    F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
    solver.solve(1, in, out);
    out.close();
  }

  static class F2MicrotransactionsHardVersion {

    public void solve(int testNumber, InputReader in, PrintWriter out) {
      int n = in.nextInt();
      int m = in.nextInt();
      int[] k = in.nextIntArrayOneBased(n);
      final int sum = IntStream.of(k).sum();
      final int maxDay = (int) 2e5;

      ArrayList<Integer>[] s = (ArrayList<Integer>[]) new ArrayList[maxDay + 1];
      for (int i = 0; i < s.length; i++) {
        s[i] = new ArrayList<>();
      }
      for (int i = 0; i < m; i++) {
        int d = in.nextInt();
        int t = in.nextInt();
        s[d].add(t);
      }

      int lo = 0, hi = (int) 5e5, ans = hi;
      while (lo <= hi) {
        int mid = (lo + hi) / 2;
        if (sum * 2 - saved(s, Arrays.copyOf(k, k.length), Math.min(mid + 1, s.length), n) <= mid) {
          hi = mid - 1;
          ans = mid;
        } else {
          lo = mid + 1;
        }
      }

      out.println(ans);
    }

    private int saved(ArrayList<Integer>[] s, int[] k, int length, int n) {
      int[] lastSale = new int[n + 1];
      for (int i = 1; i < length; i++) {
        for (int type : s[i]) {
          lastSale[type] = i;
        }
      }

      int saved = 0, has = 0;
      for (int i = 1; i < length; i++) {
        ++has;
        for (int type : s[i]) {
          if (i == lastSale[type]) {
            int win = Math.min(has, k[type]);
            saved += win;
            k[type] -= win;
            has -= win;
          }
        }
      }

      return saved;
    }

  }

  static class InputReader {

    private InputStream stream;
    private static final int DEFAULT_BUFFER_SIZE = 1 << 16;
    private static final int EOF = -1;
    private byte[] buf = new byte[DEFAULT_BUFFER_SIZE];
    private int curChar;
    private int numChars;

    public InputReader(InputStream stream) {
      this.stream = stream;
    }

    public int read() {
      if (this.numChars == EOF) {
        throw new UnknownError();
      } else {
        if (this.curChar >= this.numChars) {
          this.curChar = 0;

          try {
            this.numChars = this.stream.read(this.buf);
          } catch (IOException ex) {
            throw new InputMismatchException();
          }

          if (this.numChars <= 0) {
            return EOF;
          }
        }

        return this.buf[this.curChar++];
      }
    }

    public int nextInt() {
      int c;
      for (c = this.read(); isSpaceChar(c); c = this.read()) {
      }

      byte sgn = 1;
      if (c == 45) {
        sgn = -1;
        c = this.read();
      }

      int res = 0;

      while (c >= 48 && c <= 57) {
        res *= 10;
        res += c - 48;
        c = this.read();
        if (isSpaceChar(c)) {
          return res * sgn;
        }
      }

      throw new InputMismatchException();
    }

    public static boolean isSpaceChar(int c) {
      return c == 32 || c == 10 || c == 13 || c == 9 || c == EOF;
    }

    public int[] nextIntArrayOneBased(int n) {
      int[] ret = new int[n + 1];
      for (int i = 1; i <= n; i++) {
        ret[i] = nextInt();
      }
      return ret;
    }

  }
}

import java.io.*;
import java.util.*;

public class ProblemF_1 {

    public static InputStream inputStream = System.in;

    public static OutputStream outputStream = System.out;

    public static void main(String[] args) {
        MyScanner scanner = new MyScanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);

        int n = scanner.nextInt();
        int m = scanner.nextInt();
        List<Integer> amounts = new ArrayList<>();
        List<Pair<Integer, Integer>> salePairs = new ArrayList<>();
        int s = 0;
        for (int i = 0; i < n; i++) {
            int x = scanner.nextInt();
            s = s + x;
            amounts.add(x);
        }

        for (int i = 0; i < m; i++) {
            salePairs.add(new Pair<>(scanner.nextInt(), scanner.nextInt()));
        }

        for (int i = 1; i <= 2 * s; i++) {
            if (solve(amounts, salePairs, s, i)) {
                out.println(i);
                break;
            }
        }

        out.flush();
    }

    private static boolean solve(List<Integer> amounts, List<Pair<Integer, Integer>> salePairs, int sum, int lastDay) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < salePairs.size(); i++) {
            Pair<Integer, Integer> pair = salePairs.get(i);
            if (pair.first <= lastDay) {
                if (map.containsKey(pair.second)) {
                    if (map.get(pair.second) < pair.first) {
                        map.put(pair.second, pair.first);
                    }
                } else {
                    map.put(pair.second, pair.first);
                }
            }
        }

        Map<Integer, List<Integer>> sales = new HashMap<>();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (!sales.containsKey(entry.getValue())) {
                sales.put(entry.getValue(), new ArrayList<>());
            }
            sales.get(entry.getValue()).add(entry.getKey());
        }

        int x = 0;
        for (int i = 1; i <= lastDay; i++) {
            x++;
            if (sales.containsKey(i)) {
                for (int t : sales.get(i)) {
                    if (x > amounts.get(t - 1)) {
                        sum = sum - amounts.get(t - 1);
                        x = x - amounts.get(t - 1);
                    } else {
                        sum = sum - x;
                        x = 0;
                    }
                }
            }
            if (sum * 2 <= x) {
                break;
            }
        }
        return sum * 2 <= x;
    }

    private static class MyScanner {
        private BufferedReader bufferedReader;
        private StringTokenizer stringTokenizer;

        private MyScanner(InputStream inputStream) {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        }

        private String next() {
            while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) {
                try {
                    stringTokenizer = new StringTokenizer(bufferedReader.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return stringTokenizer.nextToken();
        }

        private int nextInt() {
            return Integer.parseInt(next());
        }

        private long nextLong() {
            return Long.parseLong(next());
        }

        private double nextDouble() {
            return Double.parseDouble(next());
        }

        private String nextLine() {
            String str = "";
            try {
                str = bufferedReader.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }

    private static class Pair<F, S> {

        private F first;

        private S second;

        public Pair() {
        }

        public Pair(F first, S second) {
            this.first = first;
            this.second = second;
        }
    }
}

import java.util.*;
public class Main {
    public static int n, m;
    public static int[] arr;
    public static TreeSet<Integer>[] set;
    public static boolean ok(int day) {
        int[] clone = arr.clone();
        int[] last = new int[n];
        for (int i = 0; i < n; i++) {
            Integer res = set[i].floor(day);
            last[i] = (res == null) ? -1 : res;
        }
        int burles = 0;
        for (int i = 0; i <= day; i++) {
            burles++;
            for (int j = 0; j < n; j++) {
                if (last[j] == i) {
                    while (clone[j] > 0 && burles > 0) {
                        burles--;
                        clone[j]--;
                    }
                }
            }
        }
        for (int i = 0; i < n; i++) {
            while (clone[i] > 0) {
                clone[i]--;
                burles -= 2;
            }
        }
        return burles >= 0;
    }
    public static void check(int l, int r) {
        if (r - l <= 5) {
            for (int i = l; i <= r; i++) {
                if (ok(i)) {
                    System.out.println(i + 1);
                    return;
                }
            }
            return;
        }
        int mid = (l + r) / 2;
        if (ok(mid)) {
            check(l, mid);
        } else {
            check(mid, r);
        }
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        m = in.nextInt();
        arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = in.nextInt();
        }
        set = new TreeSet[n];
        for (int i = 0; i < n; i++) {
            set[i] = new TreeSet<>();
        }
        for (int i = 0; i < m; i++) {
            int d = in.nextInt() - 1;
            int t = in.nextInt() - 1;
            set[t].add(d);
        }
        check(0, 10000);
    }
}

import java.io.*;
import java.util.*;
import java.math.*;

public class F{
  final int mod = 1000000007;
  final int maxn = (int)4e5 + 3;
  final double eps = 1e-9;

  int n, m;
  int[] k = new int[maxn];
  List<Integer>[] dayOffer = new ArrayList[maxn + 1];{
    for(int i = 0; i < dayOffer.length; ++i){
      dayOffer[i] = new ArrayList();
    }
  }

  boolean can(int day){
    int burles = 0;
    int[] offer = new int[maxn];
    for(int d = 1; d <= day; ++d){
      for(int i : dayOffer[d]){
        offer[i] = Math.max(offer[i], d);
      }
    }
    List<Integer>[] sale = new ArrayList[maxn];
    for(int i = 0; i < sale.length; ++i){
      sale[i] = new ArrayList<Integer>();
    }
    for(int i = 0; i < n; ++i){
      sale[offer[i]].add(i);
    }
    int[] buy = new int[maxn];
    for(int d = 1; d <= day; ++d){
      ++burles;
      for(int i : sale[d]){
        buy[i] = Math.min(k[i], burles);
        burles -= buy[i];
      }
    }
    for(int i = 0; i < n; ++i){
      burles -= 2 * (k[i] - buy[i]);
    }
    return burles >= 0;
  }

  void main(){
    // freopen("in");
    n = nextInt();
    m = nextInt();
    int sum = 0;
    for(int i = 0; i < n; ++i){
      k[i] = nextInt();
      sum += k[i];
    }
    for(int i = 0; i < m; ++i){
      int d = nextInt();
      int t = nextInt() - 1;
      dayOffer[d].add(t);
    }
    int i = 1, j = 2 * sum;
    while(i < j){
      int day = (i + j) / 2;
      if(!can(day)){
        i = day + 1;
      }
      else{
        j = day;
      }
    }
    printf("%d\n", i);
  }

  final double pi = Math.acos(-1.0);
  final long infl = 0x3f3f3f3f3f3f3f3fl;
  final int inf = 0x3f3f3f3f;
  final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

  boolean zero(double x){ return x < eps; }

  PrintWriter out = new PrintWriter(System.out);
  BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 1 << 15);
  StringTokenizer tokens = new StringTokenizer("");

  F(){
    Locale.setDefault(Locale.US);       // imprime double com ponto
    main();
    out.close();
  }

  void freopen(String s){ try{ reader = new BufferedReader(new InputStreamReader(new FileInputStream(s)), 1 << 15); } catch(FileNotFoundException e){ throw new RuntimeException(e); } }

  int nextInt(){ return Integer.parseInt(next()); }
  long nextLong(){ return Long.parseLong(next()); }
  double nextDouble(){ return Double.parseDouble(next()); }
  String next(){ readTokens(); return tokens.nextToken(); }
  String nextLine(){ readTokens(); return tokens.nextToken("\n"); }

  void readTokens(){
    while(!tokens.hasMoreTokens())      // lê os dados, ignorando linhas vazias
      try{ tokens = new StringTokenizer(reader.readLine()); } catch(IOException e){ throw new RuntimeException(e); }
  }

  void printf(String s, Object... o){ out.printf(s, o); }
  void debug(String s, Object... o){ if(!ONLINE_JUDGE) System.err.printf((char)27 + "[91m" + s + (char)27 + "[0m", o); }

  public static void main(String[] args){ new F(); }
}

import java.io.*;
import java.text.*;
import java.util.*;
import java.math.*;
public class template {
	public static void main(String[] args) throws Exception {
		new template().run();
	}
	public void run() throws Exception {
		FastScanner f = new FastScanner();
		PrintWriter out = new PrintWriter(System.out);
		int n = f.nextInt(), m = f.nextInt();
		int[] nec = new int[n];
		int tot = 0;
		for(int i = 0; i < n; i++) tot += nec[i] = f.nextInt();
		LinkedList<Integer>[] ll = new LinkedList[200000];
		for(int i = 0; i < ll.length; i++) ll[i] = new LinkedList<>();
		for(int i = 0; i < m; i++) {
			int a = f.nextInt(), b = f.nextInt();
			ll[a-1].add(b-1);
		}
		int lo = 1, hi = tot*2;
		while(lo < hi) {
			int mid = (lo+hi)/2;
			int total = tot;
			int y = mid;
			int z = mid;
			int[] cnt = new int[n];
			for(int i = mid-1; i >= 0; i--) {
				y = Math.min(y, i+1);
				if(i < ll.length) for(int a : ll[i])
					while(y > 0 && cnt[a] < nec[a]) {
						cnt[a]++;
						y--;
						z--;
						total--;
					}
			}
			if(total * 2 <= z) hi = mid;
			else lo = mid+1;
		}
		out.println(lo);
 		out.flush();
	}
	public static final long MOD = 998244353;
    static class FastScanner {
        public BufferedReader reader;
        public StringTokenizer tokenizer;
        public FastScanner() {
            reader = new BufferedReader(new InputStreamReader(System.in), 32768);
            tokenizer = null;
        }
        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }
        public int nextInt() {
            return Integer.parseInt(next());
        }
        public long nextLong() {
        	return Long.parseLong(next());
        }
        public double nextDouble() {
        	return Double.parseDouble(next());
        }
        public String nextLine() {
        	try {
        		return reader.readLine();
        	} catch(IOException e) {
        		throw new RuntimeException(e);
        	}
        }
    }
}

import java.lang.*;
import java.math.*;
import java.util.*;
import java.io.*;
public class Main {
class Node {
    int d;
    int t;
    public Node(int d,int t){
        this.d=d;
        this.t=t;
    }

}
class Node2 implements Comparable<Node2>{
    int t;
    int cnt;
    public Node2(int t,int cnt){
        this.t=t;
        this.cnt=cnt;
    }
    public int compareTo(Node2 c){
        int t=Integer.compare(this.cnt,c.cnt);
        if(t!=0) return t;
        t=Integer.compare(this.t,c.t);
        return t;
    }
}
    void solve() {
        n=ni(); m=ni();
        a=new int[n+1];
        long sm=0;
        for(int i=1;i<=n;i++){
            a[i]=ni();
            sm+=a[i];
        }
        last=new int[n+1];
         p=new Node[m+1];
         sz= new int[200001];
        cnt=new int[n+1];
        for(int i=1;i<=m;i++){
            p[i]=new Node(ni(),ni());

        }
        idx=new int[200001][];

        b=new int[n+1];
        long ans=0;
        long l=sm,r=2*sm;
        while(l<=r){
            long mid=(l+r)>>1;
            if(check(mid)) {
                ans=mid;
                r=mid-1;
            }else l=mid+1;
        }
        pw.println(ans);

    }
    int idx[][];
    int last[];
    int a[],b[];
    int n,m;
    int cnt[];
    Node p[];
    int sz[];
    PriorityQueue<Node2> q=new PriorityQueue<>();
    boolean check(long TDays){
        long B=0,mn;
        for(int i=1;i<=n;i++) b[i]=a[i];
        Arrays.fill(last,0);
        for(int i=1;i<=m;i++){
            if(p[i].d<=TDays) last[p[i].t]=Math.max(last[p[i].t],p[i].d);
        }

        for(int i=1;i<=n;i++){
            sz[last[i]]++;
        }
        for(int i=1;i<=200000;i++) idx[i]=new int[sz[i]];
        for(int i=1;i<=n;i++){
            if(last[i]==0) continue;
            idx[last[i]][--sz[last[i]]]=i;
        }

        for(int day=1;day<=(int)Math.min(TDays,200000);day++){
            B++;
            for(int t : idx[day]){
                mn=Math.min(b[t],B);
                B-=mn; b[t]-=mn;
            }

        }
        long total=0;
        for(int i=1;i<=n;i++) total+=b[i];
        B+=TDays-Math.min(TDays,200000);
        return total*2<=B;

    }

    long M =(long)1e9+7;
    InputStream is;
    PrintWriter pw;
    String INPUT = "";

    void run() throws Exception {
        is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        pw = new PrintWriter(System.out);
        long s = System.currentTimeMillis();
        solve();
        pw.flush();
        if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms");

    }

    public static void main(String[] args) throws Exception {
        new Main().run();
    }

    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;

    private int readByte() {
        if (lenbuf == -1) throw new InputMismatchException();
        if (ptrbuf >= lenbuf) {
            ptrbuf = 0;
            try {
                lenbuf = is.read(inbuf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (lenbuf <= 0) return -1;
        }
        return inbuf[ptrbuf++];
    }

    private boolean isSpaceChar(int c) {
        return !(c >= 33 && c <= 126);
    }

    private int skip() {
        int b;
        while ((b = readByte()) != -1 && isSpaceChar(b)) ;
        return b;
    }

    private double nd() {
        return Double.parseDouble(ns());
    }

    private char nc() {
        return (char) skip();
    }

    private String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n) {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while (p < n && !(isSpaceChar(b))) {
            buf[p++] = (char) b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private char[][] nm(int n, int m) {
        char[][] map = new char[n][];
        for (int i = 0; i < n; i++) map[i] = ns(m);
        return map;
    }

    private int[] na(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = ni();
        return a;
    }

    private int ni() {
        int num = 0, b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl() {
        long num = 0;
        int b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private boolean oj = System.getProperty("ONLINE_JUDGE") != null;

    private void tr(Object... o) {
        if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
    }

}

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.TreeSet;

public class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int m = in.nextInt();

    int[] wanted = new int[n];
    for (int i = 0; i < n; i += 1) {
      wanted[i] = in.nextInt();
    }

    Discount[] discounts = new Discount[m];
    for (int i = 0; i < m; i += 1) {
      int day = in.nextInt();
      int type = in.nextInt() - 1;
      discounts[i] = new Discount(type, day);
    }

    int res = solve(wanted, discounts);
    System.out.println(res);
  }

  private static int solve(final int[] wanted, Discount[] discounts) {
    DiscountCatalogue catalogue = new DiscountCatalogue(wanted.length);
    catalogue.add(discounts);

    int days = 0;
    int power = (1 << 25);

    while (power > 0) {
      int nextDays = days + power;
      power >>= 1;

      if (!canBuy(wanted, catalogue, nextDays)) {
        days = nextDays;
      }
    }
    return days + 1;
  }

  private static boolean canBuy(final int[] wanted, final DiscountCatalogue catalogue, int days) {
    ArrayList<Discount> discounts = new ArrayList<Discount>();
    int total = 0;

    for (int i = 0; i < wanted.length; i += 1) {
      total += wanted[i];

      int day = catalogue.lastDay(i, days);
      if (day != -1) {
        discounts.add(new Discount(i, day));
      }
    }

    Collections.sort(discounts);

    int needed = 0;
    for (Discount d : discounts) {
      int boughtAtDiscount = Math.min(wanted[d.type], d.day - needed);
      needed += boughtAtDiscount;
    }
    needed += 2 * (total - needed);

    return needed <= days;
  }
}

class DiscountCatalogue {
  private ArrayList<TreeSet<Integer>> discounts;

  public DiscountCatalogue(int size) {
    discounts = new ArrayList<TreeSet<Integer>>(size);
    for (int i = 0; i < size; i += 1) {
      discounts.add(new TreeSet<Integer>());
    }
  }

  public void add(final Discount[] discounts) {
    for (final Discount d : discounts) {
      add(d);
    }
  }

  public void add(final Discount discount) {
    discounts.get(discount.type).add(discount.day);
  }

  public int lastDay(int type, int finalDay) {
    Integer day = discounts.get(type).lower(finalDay + 1);
    return (day == null) ? -1 : day;
  }
}

class Discount implements Comparable<Discount> {
  public int type;
  public int day;

  public Discount(int type, int day) {
    this.type = type;
    this.day = day;
  }

  @Override
  public int compareTo(final Discount other) {
    return day - other.day;
  }
}

import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Vector;
import java.util.TreeSet;
public class CF560F1{
	public static void vectorSort(Vector<Vector<Integer>> vecs){
		Comparator<Integer> comp = new Comparator<Integer>(){
			public int compare(Integer a, Integer b){
				return Integer.compare(a,b);
			}};
		for(int i = 1; i < vecs.size();++i){
			vecs.get(i).sort(comp);
		}
	}
	public static <T> void printVecs(Vector<Vector<T>> vecs){
		for(int i = 1; i<vecs.size();++i){
			System.out.print(i + " : [");
			for(int j = 0; j<vecs.get(i).size();++j){
				System.out.print(vecs.get(i).get(j) + ", ");
			}
			System.out.println("]");
		}
	}
	public static boolean checkDay(int day, List<Integer> trans, Vector<Vector<Integer>> vecs){
		List<Integer> temp = new ArrayList<Integer>(trans);
		int bul = 0;
		for(int i = 1; i <= day;++i){
			bul++;
			for(int j = 0; j < temp.size();++j){
				if(temp.get(j) <= 0)
					continue;
				Vector<Integer> tempVec = vecs.get(j+1);
				for(int k = 0; k < tempVec.size();++k){
					if(tempVec.get(k) == i && (k + 1 == tempVec.size() || tempVec.get(k+1) > day)){
						int tempCount = temp.get(j);
						temp.set(j, Math.max(tempCount - bul, 0));
						bul = bul - tempCount + temp.get(j);
					}
				}
			}
		}
		for(int i = 0; i < temp.size();++i){
			bul -= temp.get(i) * 2;
		}
		return bul>=0;
	}

	public static void main(String[] args){
		//test();
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int m = in.nextInt();
		int sum = 0;
		List<Integer> trans = new ArrayList<>();
		Vector<Vector<Integer>> sales = new Vector<Vector<Integer>>();
		for(int i = 0;i<n;++i){
			trans.add(in.nextInt());
			sum += trans.get(i);
			sales.addElement(new Vector<Integer>());
		}
		sales.addElement(new Vector<Integer>());
		for(int i = 0;i<m;++i){
			int date = in.nextInt();
			int tran = in.nextInt();
			sales.get(tran).addElement(date);
		}
		vectorSort(sales);
		//printVecs(sales);
		int left = 0;
		int right = sum*2+1;
		int res = right;
		while(left + 1 < right){

			int middle = (left+right)/2;
			//System.out.println( left + " " + middle + " " + right);
			if(checkDay(middle,trans, sales)){
				res = middle;
				right = middle;
			} else {
				left = middle + 1;
			}
		}
		if(left < right && checkDay(left,trans, sales)) res = left;
		System.out.println(res);

	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Scanner;
import java.util.Comparator;
import java.util.Collections;
import java.util.ArrayList;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F1MicrotransactionsEasyVersion solver = new F1MicrotransactionsEasyVersion();
        solver.solve(1, in, out);
        out.close();
    }

    static class F1MicrotransactionsEasyVersion {
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            int[] reqTrans = ScannerUtils.readIntArray(in, n);
            int sumReqTrans = 0;
            for (int val : reqTrans) {
                sumReqTrans += val;
            }

            ArrayList<Integer>[] tranTypeToSpecOfferDays = new ArrayList[n];
            for (int i = 0; i < n; i++) {
                tranTypeToSpecOfferDays[i] = new ArrayList<>();
            }

            while (m-- > 0) {
                int day = in.nextInt();
                int tranType = in.nextInt() - 1;
                tranTypeToSpecOfferDays[tranType].add(day);
            }

            for (int i = 0; i < n; i++) {
                Collections.sort(tranTypeToSpecOfferDays[i]);
            }

            int lo = 1;
            int hi = sumReqTrans * 2;
            int result = -1;
            while (lo <= hi) {
                int mid = lo + (hi - lo) / 2;

                if (canBuyAll(mid, buildTransList(reqTrans, tranTypeToSpecOfferDays, mid))) {
                    result = mid;
                    hi = mid - 1;
                } else {
                    lo = mid + 1;
                }
            }

            out.println(result);
        }

        private List<F1MicrotransactionsEasyVersion.MicroTran> buildTransList(int[] reqTrans,
                                                                              ArrayList<Integer>[] tranTypeToSpecOfferDays,
                                                                              int lastDay) {
            ArrayList<F1MicrotransactionsEasyVersion.MicroTran> list = new ArrayList<>();
            for (int tranType = 0; tranType < reqTrans.length; tranType++) {
                int bsIdx =
                        ListUtils.binarySearchFirstLessThan(tranTypeToSpecOfferDays[tranType], lastDay + 1);
                int lastSpecOfferDay = bsIdx == -1 ? -1 : tranTypeToSpecOfferDays[tranType].get(bsIdx);

                list.add(new F1MicrotransactionsEasyVersion.MicroTran(tranType + 1,
                                                                      lastSpecOfferDay,
                                                                      reqTrans[tranType]));
            }
            return list;
        }

        private boolean canBuyAll(int moneyOnEndDay, List<F1MicrotransactionsEasyVersion.MicroTran> transList) {
            transList.sort(Comparator.comparingInt(mt -> mt.lastSpecOfferDay));

            int moneySpentForSpecOffers = 0;
            int transCountForLastDay = 0;
            for (F1MicrotransactionsEasyVersion.MicroTran tran : transList) {
                if (tran.lastSpecOfferDay == -1) {
                    transCountForLastDay += tran.requiredCount;
                } else {
                    int nowMoney = tran.lastSpecOfferDay - moneySpentForSpecOffers;
                    int buyCount = Math.min(nowMoney, tran.requiredCount);
                    moneySpentForSpecOffers += buyCount;
                    transCountForLastDay += tran.requiredCount - buyCount;
                }
            }

            return moneyOnEndDay - moneySpentForSpecOffers - transCountForLastDay * 2 >= 0;
        }

        private static class MicroTran {
            private final int lastSpecOfferDay;
            private final int requiredCount;
            private final int type;

            public MicroTran(int type, int lastSpecOfferDay, int requiredCount) {
                this.lastSpecOfferDay = lastSpecOfferDay;
                this.requiredCount = requiredCount;
                this.type = type;
            }

        }

    }

    static class ScannerUtils {
        public static int[] readIntArray(Scanner in, int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++) {
                array[i] = in.nextInt();
            }
            return array;
        }

    }

    static class ListUtils {
        public static <T extends Comparable<T>> int binarySearchFirstLessThan(List<T> list, T target) {
            int result = -1;
            int lo = 0;
            int hi = list.size() - 1;
            while (lo <= hi) {
                int mid = lo + (hi - lo) / 2;
                int cmpRes = list.get(mid).compareTo(target);
                if (cmpRes < 0) {
                    result = mid;
                    lo = mid + 1;
                } else {
                    hi = mid - 1;
                }
            }
            return result;
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Scanner;
import java.util.Comparator;
import java.util.Collections;
import java.util.ArrayList;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F1MicrotransactionsEasyVersion solver = new F1MicrotransactionsEasyVersion();
        solver.solve(1, in, out);
        out.close();
    }

    static class F1MicrotransactionsEasyVersion {
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            int[] reqTrans = ScannerUtils.readIntArray(in, n);
            int sumReqTrans = 0;
            for (int val : reqTrans) {
                sumReqTrans += val;
            }

            int[][] specOffers = ScannerUtils.read2dArray(in, m, 2);

            ArrayList<Integer>[] tranTypeToSpecOfferDays = new ArrayList[n];
            for (int i = 0; i < n; i++) {
                tranTypeToSpecOfferDays[i] = new ArrayList<>();
            }

            for (int[] specOffer : specOffers) {
                tranTypeToSpecOfferDays[specOffer[1] - 1].add(specOffer[0]);
            }

            for (int i = 0; i < n; i++) {
                Collections.sort(tranTypeToSpecOfferDays[i]);
            }

            int lo = 1;
            int hi = sumReqTrans * 2;
            int result = -1;
            while (lo <= hi) {
                int mid = lo + (hi - lo) / 2;

                if (canBuyAll(mid, buildTransList(reqTrans, tranTypeToSpecOfferDays, mid))) {
                    result = mid;
                    hi = mid - 1;
                } else {
                    lo = mid + 1;
                }
            }

            out.println(result);
        }

        private List<F1MicrotransactionsEasyVersion.MicroTran> buildTransList(int[] reqTrans,
                                                                              ArrayList<Integer>[] tranTypeToSpecOfferDays,
                                                                              int lastDay) {
            ArrayList<F1MicrotransactionsEasyVersion.MicroTran> list = new ArrayList<>();
            for (int tranType = 0; tranType < reqTrans.length; tranType++) {
                int bsIdx =
                        ListUtils.binarySearchFirstLessThan(tranTypeToSpecOfferDays[tranType], lastDay + 1);
                int lastSpecOfferDay = bsIdx == -1 ? -1 : tranTypeToSpecOfferDays[tranType].get(bsIdx);

                list.add(new F1MicrotransactionsEasyVersion.MicroTran(tranType + 1,
                                                                      lastSpecOfferDay,
                                                                      reqTrans[tranType]));
            }
            return list;
        }

        private boolean canBuyAll(int moneyOnEndDay, List<F1MicrotransactionsEasyVersion.MicroTran> transList) {
            transList.sort(Comparator.comparingInt(mt -> mt.lastSpecOfferDay));

            int moneySpentForSpecOffers = 0;
            int transCountForLastDay = 0;
            for (F1MicrotransactionsEasyVersion.MicroTran tran : transList) {
                if (tran.lastSpecOfferDay == -1) {
                    transCountForLastDay += tran.requiredCount;
                } else {
                    int nowMoney = tran.lastSpecOfferDay - moneySpentForSpecOffers;
                    int buyCount = Math.min(nowMoney, tran.requiredCount);
                    moneySpentForSpecOffers += buyCount;
                    transCountForLastDay += tran.requiredCount - buyCount;
                }
            }

            return moneyOnEndDay - moneySpentForSpecOffers - transCountForLastDay * 2 >= 0;
        }

        private static class MicroTran {
            private final int lastSpecOfferDay;
            private final int requiredCount;
            private final int type;

            public MicroTran(int type, int lastSpecOfferDay, int requiredCount) {
                this.lastSpecOfferDay = lastSpecOfferDay;
                this.requiredCount = requiredCount;
                this.type = type;
            }

        }

    }

    static class ScannerUtils {
        public static int[] readIntArray(Scanner in, int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++) {
                array[i] = in.nextInt();
            }
            return array;
        }

        public static int[][] read2dArray(Scanner in, int rows, int cols) {
            int[][] arr = new int[rows][cols];
            for (int row = 0; row < rows; row++) {
                for (int col = 0; col < cols; col++) {
                    arr[row][col] = in.nextInt();
                }
            }
            return arr;
        }

    }

    static class ListUtils {
        public static <T extends Comparable<T>> int binarySearchFirstLessThan(List<T> list, T target) {
            int result = -1;
            int lo = 0;
            int hi = list.size() - 1;
            while (lo <= hi) {
                int mid = lo + (hi - lo) / 2;
                int cmpRes = list.get(mid).compareTo(target);
                if (cmpRes < 0) {
                    result = mid;
                    lo = mid + 1;
                } else {
                    hi = mid - 1;
                }
            }
            return result;
        }

    }
}

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

public class _1165_F1 {

	public static void main(String[] args) throws Exception {
		FastScanner sc = new FastScanner(System.in);
		FastPrinter out = new FastPrinter(System.out);
		run(sc, out);
		out.close();
	}

	public static void run(FastScanner sc, FastPrinter out) throws Exception {
		int N = sc.nextInt();
		int M = sc.nextInt();
		remainingSales = new int[N];
		int[][] sales = new int[M][2];
		int total = 0;
		int[] arr = new int[N];
		for (int i = 0; i < N; i++) {
			arr[i] = sc.nextInt();
			total += arr[i];
		}
		total *= 2;
		for (int i = 0; i < M; i++) {
			int a = sc.nextInt();
			int b = sc.nextInt() - 1;
			sales[i][0] = a;
			sales[i][1] = b;
		}
		Arrays.sort(sales, (a, b) -> a[0] - b[0]);
		int[] arrC = new int[N];
		int low = 0;
		int high = total;
		while (low <= high) {
			int mid = (low + high) / 2;
			for (int i = 0; i < N; i++) {
				arrC[i] = arr[i];
			}
			if (works(mid, arrC, sales, total)) {
				high = mid - 1;

			} else {
				low = mid + 1;
			}
		}
		System.out.println(low);
		// for (int day = 0;; day++) {
		// if (works(day, arrC, sales, total)) {
		// System.out.println(day);
		// return;
		// }
		// }

	}

	static int[] remainingSales;

	private static boolean works(int day, int[] arr, int[][] sales, int total) {
		Arrays.fill(remainingSales, 0);
		for (int[] s : sales) {
			int d = s[0];
			int t = s[1];
			if (d > day) break;
			remainingSales[t]++;
		}
		int saved = 0;
		int amt = 0;
		int pDay = 0;
		for (int[] s : sales) {
			int d = s[0];
			int t = s[1];
			if (d > day) break;
			amt += d - pDay;
			pDay = d;
			if (--remainingSales[t] == 0) {
				int bought = Math.min(arr[t], amt);
				arr[t] -= bought;
				amt -= bought;
				saved += bought;
			}
		}
		return day + saved >= total;
	}

	static class FastPrinter {
		static final char ENDL = '\n';
		StringBuilder buf;
		PrintWriter pw;

		public FastPrinter(OutputStream stream) {
			buf = new StringBuilder();
			pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
		}

		public FastPrinter(String fileName) throws Exception {
			buf = new StringBuilder();
			pw = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
		}

		public FastPrinter(StringBuilder buf) {
			this.buf = buf;
		}

		public void print(int a) {
			buf.append(a);
		}

		public void print(long a) {
			buf.append(a);
		}

		public void print(char a) {
			buf.append(a);
		}

		public void print(char[] a) {
			buf.append(a);
		}

		public void print(double a) {
			buf.append(a);
		}

		public void print(String a) {
			buf.append(a);
		}

		public void print(Object a) {
			buf.append(a.toString());
		}

		public void println() {
			buf.append(ENDL);
		}

		public void println(int a) {
			buf.append(a);
			buf.append(ENDL);
		}

		public void println(long a) {
			buf.append(a);
			buf.append(ENDL);
		}

		public void println(char a) {
			buf.append(a);
			buf.append(ENDL);
		}

		public void println(char[] a) {
			buf.append(a);
			buf.append(ENDL);
		}

		public void println(double a) {
			buf.append(a);
			buf.append(ENDL);
		}

		public void println(String a) {
			buf.append(a);
			buf.append(ENDL);
		}

		public void println(Object a) {
			buf.append(a.toString());
			buf.append(ENDL);
		}

		public void printf(String format, Object... args) {
			buf.append(String.format(format, args));
		}

		public void close() {
			pw.print(buf);
			pw.close();
		}

		public void flush() {
			pw.print(buf);
			pw.flush();
			buf.setLength(0);
		}

	}

	static class FastScanner {
		final private int BUFFER_SIZE = 1 << 10;
		private DataInputStream din;
		private byte[] buffer;
		private int bufferPointer, bytesRead;

		public FastScanner(InputStream stream) {
			din = new DataInputStream(stream);
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}

		public FastScanner(String fileName) throws IOException {
			Path p = Paths.get(fileName);
			buffer = Files.readAllBytes(p);
			bytesRead = buffer.length;
		}

		int[] nextIntArray(int N) throws IOException {
			int[] arr = new int[N];
			for (int i = 0; i < N; i++) {
				arr[i] = nextInt();
			}
			return arr;
		}

		String nextLine() throws IOException {
			int c = read();
			while (c != -1 && isEndline(c))
				c = read();
			if (c == -1) {
				return null;
			}
			StringBuilder res = new StringBuilder();
			do {
				if (c >= 0) {
					res.appendCodePoint(c);
				}
				c = read();
			} while (!isEndline(c));
			return res.toString();
		}

		boolean isEndline(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}

		String next() throws Exception {
			int c = readOutSpaces();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		public int nextInt() throws IOException {
			int ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg) c = read();
			do {
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');

			if (neg) return -ret;
			return ret;
		}

		public long nextLong() throws IOException {
			long ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg) c = read();
			do {
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');
			if (neg) return -ret;
			return ret;
		}

		public double nextDouble() throws IOException {
			double ret = 0, div = 1;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg) c = read();

			do {
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');

			if (c == '.') {
				while ((c = read()) >= '0' && c <= '9') {
					ret += (c - '0') / (div *= 10);
				}
			}

			if (neg) return -ret;
			return ret;
		}

		private void fillBuffer() throws IOException {
			bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
			if (bytesRead == -1) buffer[0] = -1;
		}

		private byte read() throws IOException {
			if (bufferPointer == bytesRead) fillBuffer();
			return buffer[bufferPointer++];
		}

		private int readOutSpaces() throws IOException {
			while (true) {
				if (bufferPointer == bytesRead) fillBuffer();
				int c = buffer[bufferPointer++];
				if (!isSpaceChar(c)) {
					return c;
				}
			}
		}

		public void close() throws IOException {
			if (din == null) return;
			din.close();
		}
	}

}

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

public class Main {

	static class Task {

		int NN = 200005;
		int MOD = 1000000007;
		int INF = 2000000000;
		long INFINITY = 2000000000000000000L;

		List<Integer> [] o = new ArrayList[NN];
		int [] k = new int[NN];
		int [] last = new int[NN];
		int [] d;
		int [] t;

		public void solve(InputReader in, PrintWriter out) {
			int n = in.nextInt(), m = in.nextInt();
			long total = 0;
			for(int i=1;i<=n;++i) {
				k[i] = in.nextInt();
				total += 1L * k[i];
			}
			d = new int[m + 1];
			t = new int[m + 1];
			for(int i=1;i<=m;++i) {
				d[i] = in.nextInt();
				t[i] = in.nextInt();
			}
			long lo = 0, hi = 2L * total, mid = 0;
			while(lo < hi) {
				mid = (lo + hi) / 2;
				if(valid(mid, n, m))
					hi = mid;
				else
					lo = mid + 1;
			}
			out.println(lo);
		}

		long [] r = new long[NN];

		boolean valid(long targetDay, int n, int m) {
			for(int i=1;i<NN;++i) {
				r[i] = k[i];
				o[i] = new ArrayList<>();
				last[i] = 0;
			}
			for(int i=1;i<=m;++i) {
				if(d[i] <= targetDay) {
					last[t[i]] = Math.max(last[t[i]], d[i]);
				}
			}
			for(int i=1;i<=n;++i) {
				if(last[i] > 0) {
					o[last[i]].add(i);
				}
			}
			long dMin = Math.min(targetDay, NN-2);
			long coins = 0;
			for(long day=1;day<=dMin;++day) {
				++coins;
				for(int item: o[(int)day]) {
					long need = r[item];
					long take = Math.min(need, coins);
					r[item] -= take;
					coins -= take;
				}
			}
			long remainingItems = 0;
			for(int i=1;i<NN;++i) {
				remainingItems += 1L * r[i];
			}
			coins += targetDay-dMin;
			return 2L * remainingItems <= coins;
		}

	}

	static void prepareIO(boolean isFileIO) {
		//long t1 = System.currentTimeMillis();
		Task solver = new Task();
		// Standard IO
		if(!isFileIO) {
			InputStream inputStream = System.in;
	        OutputStream outputStream = System.out;
	        InputReader in = new InputReader(inputStream);
	        PrintWriter out = new PrintWriter(outputStream);
	        solver.solve(in, out);
	        //out.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0);
	        out.close();
		}
        // File IO
		else {
			String IPfilePath = System.getProperty("user.home") + "/Downloads/ip.in";
	        String OPfilePath = System.getProperty("user.home") + "/Downloads/op.out";
	        InputReader fin = new InputReader(IPfilePath);
	        PrintWriter fout = null;
	        try {
				fout = new PrintWriter(new File(OPfilePath));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
	        solver.solve(fin, fout);
	        //fout.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0);
	        fout.close();
		}
	}

	public static void main(String[] args) {
        prepareIO(false);
	}

	static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public InputReader(String filePath) {
        	File file = new File(filePath);
            try {
				reader = new BufferedReader(new FileReader(file));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            tokenizer = null;
        }

        public String nextLine() {
        	String str = "";
        	try {
				str = reader.readLine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	return str;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public long nextLong() {
            return Long.parseLong(next());
        }

        public double nextDouble() {
        	return Double.parseDouble(next());
        }

    }

}

import java.io.*;
import java.util.*;

public class CF1165F2 {
	static int search(int[] dd, int d) {
		int lower = -1, upper = dd.length;
		while (upper - lower > 1) {
			int i = (lower + upper) / 2;
			if (dd[i] <= d)
				lower = i;
			else
				upper = i;
		}
		return lower == -1 ? 0 : dd[lower];
	}
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		int n = Integer.parseInt(st.nextToken());
		int m = Integer.parseInt(st.nextToken());
		st = new StringTokenizer(br.readLine());
		int[] kk = new int[n];
		int ksum = 0;
		for (int i = 0; i < n; i++)
			ksum += kk[i] = Integer.parseInt(st.nextToken());
		ArrayList[] ll = new ArrayList[n];
		for (int i = 0; i < n; i++)
			ll[i] = new ArrayList<Integer>();
		for (int j = 0; j < m; j++) {
			st = new StringTokenizer(br.readLine());
			int d = Integer.parseInt(st.nextToken());
			int i = Integer.parseInt(st.nextToken()) - 1;
			ll[i].add(d);
		}
		int[][] dd = new int[n][];
		for (int i = 0; i < n; i++) {
			ArrayList<Integer> l = ll[i];
			Collections.sort(l);
			m = l.size();
			dd[i] = new int[m];
			m = 0;
			for (int d : l)
				dd[i][m++] = d;
		}
		Integer[] ii = new Integer[n];
		for (int i = 0; i < n; i++)
			ii[i] = i;
		int[] dos = new int[n];
		int lower = 0, upper = ksum * 2;
		while (upper - lower > 1) {
			int d = (lower + upper) / 2;
			for (int i = 0; i < n; i++)
				dos[i] = search(dd[i], d);
			Arrays.sort(ii, (i, j) -> dos[i] - dos[j]);
			int savings = 0;
			for (int h = 0; h < n; h++) {
				int i = ii[h];
				savings += Math.min(dos[i] - savings, kk[i]);
			}
			if (d + savings >= ksum * 2)
				upper = d;
			else
				lower = d;
		}
		System.out.println(upper);
	}
}

import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringJoiner;
import java.util.StringTokenizer;
import java.util.function.IntPredicate;

public class Main {

    static int N, M;
    static int[] K;
    static int[][] DT;

    public static void main(String[] args) {
        FastScanner sc = new FastScanner(System.in);
        N = sc.nextInt();
        M = sc.nextInt();
        K = sc.nextIntArray(N);
        DT = new int[M][2];
        for (int i = 0; i < M; i++) {
            DT[i][0] = sc.nextInt();
            DT[i][1] = sc.nextInt()-1;
        }

        System.out.println(solve());
    }

    static int[] LAST;
    static int S;
    static int[] R;

    static int solve(int n, int m, int[] k, int[][] dt) {
        N = n;
        M = m;
        K = k;
        DT = dt;
        return solve();
    }

    static int solve() {
        S = 0;
        for (int i = 0; i < N; i++) {
            S += K[i];
        }
        Arrays.sort(DT, Comparator.comparingInt(dt -> dt[0]));

        // 最後にセール以外で買う意味がないので調べておく
        LAST = new int[N];
        R = new int[N];

        return minimize(1, S *2+1, Main::calc);
    }

    // day日で終わるかどうか
    static boolean calc(int maxDay) {
        System.arraycopy(K, 0, R, 0, N);

        // 最後にセール以外で買う意味がないので調べておく
        Arrays.fill(LAST, -1);
        for (int i = 0; i < M; i++) {
            int d = DT[i][0];
            int t = DT[i][1];
            if( d <= maxDay ) {
                LAST[t] = d;
            }
        }

        int idx = 0;
        int money = 0;
        int bought = 0;
        for (int day = 1; day <= maxDay; day++) {
            money++;

            while( idx < M ) {
                if( DT[idx][0] < day ) {
                    idx++;

                } else if( DT[idx][0] > day ) {
                    break;

                } else {
                    int type = DT[idx][1];
                    if( day == LAST[type] ) {
                        int buy = Math.min(money, R[type]);
                        money -= buy;
                        R[type] -= buy;
                        bought += buy;
                    }
                    idx++;
                }
            }
            // debug(d, bought);
        }

        return (S - bought) * 2 <= money;
    }

    static int minimize(int lo, int hi, IntPredicate p) {
        while(lo < hi) {
            int x = ((hi - lo) >>> 1) + lo;
            if( p.test(x) ) {
                hi = x;
            } else {
                lo = x + 1;
            }
        }
        return lo;
    }

    @SuppressWarnings("unused")
    static class FastScanner {
        private BufferedReader reader;
        private StringTokenizer tokenizer;

        FastScanner(InputStream in) {
            reader = new BufferedReader(new InputStreamReader(in));
            tokenizer = null;
        }

        String next() {
            if (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        String nextLine() {
            if (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    return reader.readLine();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken("\n");
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        int[] nextIntArray(int n) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++) a[i] = nextInt();
            return a;
        }

        int[] nextIntArray(int n, int delta) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++) a[i] = nextInt() + delta;
            return a;
        }

        long[] nextLongArray(int n) {
            long[] a = new long[n];
            for (int i = 0; i < n; i++) a[i] = nextLong();
            return a;
        }
    }

    static void writeLines(int[] as) {
        PrintWriter pw = new PrintWriter(System.out);
        for (int a : as) pw.println(a);
        pw.flush();
    }

    static void writeLines(long[] as) {
        PrintWriter pw = new PrintWriter(System.out);
        for (long a : as) pw.println(a);
        pw.flush();
    }

    static void writeSingleLine(int[] as) {
        PrintWriter pw = new PrintWriter(System.out);
        for (int i = 0; i < as.length; i++) {
            if (i != 0) pw.print(" ");
            pw.print(as[i]);
        }
        pw.println();
        pw.flush();
    }

    static int max(int... as) {
        int max = Integer.MIN_VALUE;
        for (int a : as) max = Math.max(a, max);
        return max;
    }

    static int min(int... as) {
        int min = Integer.MAX_VALUE;
        for (int a : as) min = Math.min(a, min);
        return min;
    }

    static void debug(Object... args) {
        StringJoiner j = new StringJoiner(" ");
        for (Object arg : args) {
            if (arg == null) j.add("null");
            else if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg));
            else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg));
            else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg));
            else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg));
            else j.add(arg.toString());
        }
        System.err.println(j.toString());
    }

    static void printSingleLine(int[] array) {
        PrintWriter pw = new PrintWriter(System.out);
        for (int i = 0; i < array.length; i++) {
            if (i != 0) pw.print(" ");
            pw.print(array[i]);
        }
        pw.println();
        pw.flush();
    }

    static int lowerBound(int[] array, int value) {
        int lo = 0, hi = array.length, mid;
        while (lo < hi) {
            mid = (hi + lo) / 2;
            if (array[mid] < value) lo = mid + 1;
            else hi = mid;
        }
        return lo;
    }

    static int upperBound(int[] array, int value) {
        int lo = 0, hi = array.length, mid;
        while (lo < hi) {
            mid = (hi + lo) / 2;
            if (array[mid] <= value) lo = mid + 1;
            else hi = mid;
        }
        return lo;
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Vadim
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastScanner in = new FastScanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        r560F solver = new r560F();
        solver.solve(1, in, out);
        out.close();
    }

    static class r560F {
        private int binarySearch(Sale[] sales, int day) {
            int left = 0, right = sales.length;
            while (left < right) {
                int mid = (left + right) / 2;
                if (sales[mid].d <= day) {
                    left = mid + 1;
                } else {
                    right = mid;
                }
            }
            return left - 1;
        }

        public void solve(int testNumber, FastScanner in, PrintWriter out) {
            int N = in.ni(), M = in.ni();
            int[] k = in.na(N);
            Sale[] sales = new Sale[M];
            for (int i = 0; i < M; i++) {
                sales[i] = new Sale(in.ni(), in.ni() - 1, i);
            }
            Arrays.sort(sales, (x, y) -> {
                if (x.d == y.d)
                    return Integer.compare(x.id, y.id);
                else return Integer.compare(x.d, y.d);
            });
            int left = 0, right = 400_005;
            int[] krem = new int[N];
            while (left < right) {
                int mid = (left + right) / 2;
                int from = binarySearch(sales, mid);
                System.arraycopy(k, 0, krem, 0, N);
                int rem = mid;
                int spent = 0;
//            System.out.println("mid = " + mid);
                for (int i = from; i >= 0 && rem > 0; --i) {
                    Sale sale = sales[i];
                    rem = Math.min(rem, sale.d);
                    if (krem[sale.t] > 0) {
                        int available = Math.min(rem, krem[sale.t]);
                        rem -= available;
                        spent += available;
                        krem[sale.t] -= available;
                    }
                }
                rem = mid - spent;
//            System.out.println("rem = " + rem);
//            System.out.println("Arrays.toString(krem) = " + Arrays.toString(krem));
                boolean correct = true;
                for (int i = 0; i < N; i++) {
                    if (krem[i] > 0) {
                        rem -= krem[i] * 2;
                    }
                }
//            System.out.println("final rem = " + rem);
                if (rem < 0)
                    correct = false;

                if (!correct) {
                    left = mid + 1;
                } else {
                    right = mid;
                }
            }
            out.println(left);
        }

        class Sale {
            int d;
            int t;
            int id;

            public Sale(int d, int t, int id) {
                this.d = d;
                this.t = t;
                this.id = id;
            }

        }

    }

    static class FastScanner {
        private BufferedReader in;
        private StringTokenizer st;

        public FastScanner(InputStream stream) {
            in = new BufferedReader(new InputStreamReader(stream));
        }

        public String ns() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    String rl = in.readLine();
                    if (rl == null) {
                        return null;
                    }
                    st = new StringTokenizer(rl);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return st.nextToken();
        }

        public int ni() {
            return Integer.parseInt(ns());
        }

        public int[] na(int n) {
            int[] ret = new int[n];
            for (int i = 0; i < n; i++) {
                ret[i] = ni();
            }
            return ret;
        }

    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;

public class Main {

    public static void main(String[] args) throws IOException {
        StreamTokenizer streamTokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        streamTokenizer.nextToken();
        int n = (int) streamTokenizer.nval;
        streamTokenizer.nextToken();
        int m = (int) streamTokenizer.nval;

        int[] a = new int[n + 1];
        int count = 0;
        for (int i = 1; i <= n; i++) {
            streamTokenizer.nextToken();
            a[i] = (int) streamTokenizer.nval;
            count += a[i];
        }

        int[] b = new int[m + 1];
        int[] c = new int[m + 1];
        for (int i = 1; i <= m; i++) {
            streamTokenizer.nextToken();
            b[i] = (int) streamTokenizer.nval;
            streamTokenizer.nextToken();
            c[i] = (int) streamTokenizer.nval;
        }

        quickSort(b, c, 1, m);
//        int temp;
//        for (int i = 1; i <= m; i++)
//            for (int j = i + 1; j <= m; j++)
//                if (b[i] < b[j]) {
//                    temp = b[i];
//                    b[i] = b[j];
//                    b[j] = temp;
//                    temp = c[i];
//                    c[i] = c[j];
//                    c[j] = temp;
//                }

        int[] d = new int[n + 1];

        int min = count, max = count * 2, mid, result = 0;
        int money, consume, consumeCount, index;
        while (min <= max) {
            mid = (min + max) / 2;
            consumeCount = 0;
            money = mid;
            for (index = 1; index <= m && b[index] > mid; index++) ;
            for (int i = 1; i <= n; i++)
                d[i] = a[i];
            for (; index <= m; index++) {
                money = Math.min(money, b[index]);
                consume = Math.min(d[c[index]], money);
                money -= consume;
                d[c[index]] -=consume;
                consumeCount += consume;
            }
            if (mid - consumeCount >= (count - consumeCount) * 2) {
                result = mid;
                max = mid - 1;
            } else {
                min = mid + 1;
            }
        }
        System.out.println(result);
    }

    public static void quickSort(int[] a, int[] b, int l, int r) {
        int mid = a[(l + r) / 2], temp;
        int x = l, y = r;
        while (x <= y) {
            while (x <= y && a[x] > mid) x++;
            while (y >= x && a[y] < mid) y--;
            if (x <= y) {
                temp = a[x];
                a[x] = a[y];
                a[y] = temp;
                temp = b[x];
                b[x] = b[y];
                b[y] = temp;
                x++;
                y--;
            }
        }
        if (x < r)
            quickSort(a, b, x, r);
        if (y > l)
            quickSort(a, b, l, y);
    }

}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {

    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F1MikrotranzakciiUproshennayaVersiya solver = new F1MikrotranzakciiUproshennayaVersiya();
        solver.solve(1, in, out);
        out.close();
    }

    static class F1MikrotranzakciiUproshennayaVersiya {

        int[] a;
        List<Item> items;
        int sum;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            a = new int[n];
            sum = 0;
            for (int i = 0; i < n; i++) {
                a[i] = in.nextInt();
                sum += a[i];
            }

            items = new ArrayList<>();
            for (int i = 0; i < m; i++) {
                items.add(new Item(in.nextInt(), in.nextInt() - 1));
            }
            items.sort(Comparator.comparingInt(x -> x.day));

            int[] last = new int[n];
            Arrays.fill(last, -1);
            for (int i = m - 1; i >= 0; i--) {
                Item item = items.get(i);
                if (last[item.game] != -1) {
                    item.nextDay = last[item.game];
                }
                last[item.game] = item.day;
            }

            int t1 = 0;
            int t2 = (int) 1e5 + 1;
            while (t1 < t2) {
                int mid = (t1 + t2) / 2;
                if (isPossible(mid)) {
                    t2 = mid;
                } else {
                    t1 = mid + 1;
                }
            }
            out.println(t1);
        }

        private boolean isPossible(int until) {
            int idx = 0;
            int lastStop = 0;
            int money = 0;
            int taken = 0;
            while (idx < items.size() && items.get(idx).day <= until) {
                Item item = items.get(idx);
                if (item.nextDay <= until) {
                    idx++;
                    continue;
                }
                money += item.day - lastStop;
                lastStop = item.day;
                int toTake = Math.min(money, a[item.game]);
                taken += toTake;
                money -= toTake;
                idx++;
            }
            money += until - lastStop;
            return (sum - taken) * 2 <= money;
        }

        class Item {

            int day;
            int game;
            int nextDay = (int) 1e6;

            public Item(int day, int game) {
                this.day = day;
                this.game = game;
            }
        }
    }

    static class InputReader {

        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }
    }
}

import java.util.*;
import java.io.*;
import static java.lang.Math.*;
import java.math.BigInteger;
public class Main {
    static final long MOD = 998244353, INF = 1_000_000_000_000_000L;
    static final int INf = 1_000_000_000;
    static FastReader reader;
    static PrintWriter writer;
    public static void main(String[] args) {
        Thread t = new Thread(null, new O(), "Integer.MAX_VALUE", 100000000);
        t.start();
    }
    static class O implements Runnable {
        public void run() {
            try {
                magic();
            }
            catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
    }
    static class FastReader {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public FastReader() {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public FastReader(String file_name) throws IOException {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException {
            byte[] buf = new byte[1000000];
            int cnt = 0, c;
            while ((c = read()) != -1) {
                if (c == '\n') break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException {
            int ret = 0;
            byte c = read();
            while (c <= ' ') c = read();
            boolean neg = (c == '-');
            if (neg) c = read();
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (neg) return -ret;
            return ret;
        }

        public long nextLong() throws IOException {
            long ret = 0;
            byte c = read();
            while (c <= ' ') c = read();
            boolean neg = (c == '-');
            if (neg) c = read();
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (neg) return -ret;
            return ret;
        }

        public double nextDouble() throws IOException {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ') c = read();
            boolean neg = (c == '-');
            if (neg) c = read();
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10);
            if (neg) return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1) buffer[0] = -1;
        }

        private byte read() throws IOException {
            if (bufferPointer == bytesRead) fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException {
            if (din == null) return;
            din.close();
        }
    }
    static int n,m,k[],rem[];
    static Pair offers[];
    static TreeSet<Integer> offers_at[];
    static void magic() throws IOException {
        reader = new FastReader();
        writer = new PrintWriter(System.out, true);
        n = reader.nextInt();
        m = reader.nextInt();
        k = new int[n];
        rem = new int[n];
        for(int i=0;i<n;++i) {
            k[i] = reader.nextInt();
        }
        offers = new Pair[m];
        offers_at = new TreeSet[n];
        for(int i=0;i<n;++i) {
            offers_at[i] = new TreeSet<>();
        }
        for(int i=0;i<m;++i) {
            offers[i] = new Pair(reader.nextInt(), reader.nextInt()-1);
            offers_at[offers[i].y].add(offers[i].x);
        }
        Arrays.sort(offers);
        int low = 1, high = 4000000, mid;
        while(low<high) {
            mid = (low+high)>>1;
            if(check(mid)) {
                if(!check(mid-1)) {
                    low = mid;
                    break;
                }
                else high = --mid;
            }
            else low = ++mid;
        }
        writer.println(low);
    }
    static boolean check(int D) {
        for(int i=0;i<n;++i) {
            rem[i] = k[i];
        }
        int curr = 0, prev = 0;
        for(int i=0;i<m;++i) {
            if(offers[i].x>D) {
                break;
            }
            curr+=(offers[i].x - prev);
            prev = offers[i].x;
            if(offers_at[offers[i].y].lower(D+1)==offers[i].x) {
                int liya = min(curr, rem[offers[i].y]);
                curr-=liya;
                rem[offers[i].y]-=liya;
            }
            else {
                continue;
            }
        }
        curr+=(D-prev);
        int left = 0;
        for(int i=0;i<n;++i) {
            left+=rem[i];
        }
        return curr>=2*left;
    }
    static class Pair implements Comparable<Pair>
    {
        int x,y;
        Pair(int x,int y)
        {
            this.x=x;
            this.y=y;
        }
        public int compareTo(Pair other)
        {
            if(this.x!=other.x)
                return this.x-other.x;
            return this.y-other.y;
        }
        public String toString()
        {
            return "("+x+","+y+")";
        }
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
        thread.start();
        thread.join();
    }

    static class TaskAdapter implements Runnable {
        @Override
        public void run() {
            InputStream inputStream = System.in;
            OutputStream outputStream = System.out;
            FastInput in = new FastInput(inputStream);
            FastOutput out = new FastOutput(outputStream);
            F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class F2MicrotransactionsHardVersion {
        long inf = (long) 1e18;

        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.readInt();
            int m = in.readInt();
            int[] k = new int[n];
            int[] remains = new int[n];
            for (int i = 0; i < n; i++) {
                k[i] = in.readInt();
            }

            Discount[] discounts = new Discount[m];
            for (int j = 0; j < m; j++) {
                discounts[j] = new Discount();
                discounts[j].d = in.readInt();
                discounts[j].t = in.readInt() - 1;
            }

            Arrays.sort(discounts, (a, b) -> a.d - b.d);
            long[] lastDay = new long[n];
            Arrays.fill(lastDay, inf);
            for (int i = m - 1; i >= 0; i--) {
                discounts[i].nextDay = lastDay[discounts[i].t];
                lastDay[discounts[i].t] = discounts[i].d;
            }

            LongBinarySearch bs = new LongBinarySearch() {

                public boolean check(long mid) {
                    long used = 0;
                    System.arraycopy(k, 0, remains, 0, n);
                    for (int i = 0; i < m && discounts[i].d <= mid; i++) {
                        if (discounts[i].nextDay <= mid) {
                            continue;
                        }
                        int consume = (int) Math.min(discounts[i].d - used, remains[discounts[i].t]);
                        used += consume;
                        remains[discounts[i].t] -= consume;
                    }
                    for (int i = 0; i < n; i++) {
                        used += 2 * remains[i];
                    }
                    return used <= mid;
                }
            };

            long ans = bs.binarySearch(0, (long) 1e11);
            out.println(ans);
        }

    }

    static class Discount {
        int d;
        int t;
        long nextDay;

    }

    static class FastInput {
        private final InputStream is;
        private byte[] buf = new byte[1 << 13];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

    }

    static class FastOutput implements AutoCloseable, Closeable {
        private StringBuilder cache = new StringBuilder(10 << 20);
        private final Writer os;

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput println(long c) {
            cache.append(c).append('\n');
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }

    static abstract class LongBinarySearch {
        public abstract boolean check(long mid);

        public long binarySearch(long l, long r) {
            if (l > r) {
                throw new IllegalArgumentException();
            }
            while (l < r) {
                long mid = (l + r) >>> 1;
                if (check(mid)) {
                    r = mid;
                } else {
                    l = mid + 1;
                }
            }
            return l;
        }

    }
}

import java.io.*;
import java.util.*;

public class Codechef {

    static class MyScanner{
        BufferedReader br;
	StringTokenizer st;

	MyScanner(FileReader fileReader){
            br = new BufferedReader(fileReader);
	}

	MyScanner(){
            br = new BufferedReader(new InputStreamReader(System.in));
	}

	String nn(){
            while(st == null || !st.hasMoreElements()){
		try{
                    st = new StringTokenizer(br.readLine());
		}catch(IOException e){
                    e.printStackTrace();
		}
            }
            return st.nextToken();
	}

	char nc(){
            return nn().charAt(0);
	}

	int ni(){
            return Integer.parseInt(nn());
	}

	long nl(){
            return Long.parseLong(nn());
	}

	double nd(){
            return Double.parseDouble(nn());
	}

	int[] niArr0(int n){
            int[] ar = new int[n];
            for(int i = 0; i < n; i++) ar[i] = ni();
            return ar;
	}

        int[] niArr1(int n){
            int[] ar = new int[n + 1];
            for(int i = 1; i <= n; i++) ar[i] = ni();
            return ar;
	}

        long[] nlArr0(int n){
            long[] ar = new long[n];
            for(int i = 0; i < n; i++) ar[i] = nl();
            return ar;
        }

        long[] nlArr1(int n){
            long[] ar = new long[n + 1];
            for(int i = 1; i <= n; i++) ar[i] = nl();
            return ar;
        }
    }

    public static <T> void mprintln(T ... ar){
        for(T i: ar) out.print(i + " ");
        out.println();
    }

    private static PrintWriter out;

    public static void main(String[] args) throws FileNotFoundException{

        // Input from file
        // File inputFile = new File("JavaFile.txt");
        // File outputFile = new File("JavaOutputFile.txt");
        // FileReader fileReader = new FileReader(inputFile);
        // Here it ends

        MyScanner sc = new MyScanner();
        // MyScanner sc = new MyScanner(fileReader);

        out = new PrintWriter(new BufferedOutputStream(System.out)); // Output to console
        // out = new PrintWriter(new PrintStream(outputFile)); // Output to file

        getAns(sc);

        out.close();
    }

    private static void getAns(MyScanner sc){
        int n = sc.ni(), m = sc.ni();
        int[] k = sc.niArr0(n);
        HashMap<Integer, NavigableSet<Integer>> map = new HashMap();

        for(int i = 0; i < m; i++){
            int day = sc.ni(), type = sc.ni();
            map.putIfAbsent(type, new TreeSet());
            map.get(type).add(day);
        }

//        out.println(map);

        int start = 1, end = 2 * (int)1e5;
        int ans = end;

//        out.println(map);

        while(start <= end){
            int mid = start + end >> 1;
            if(OK(mid, getMapAccordingly(map, mid), Arrays.copyOf(k, n), n)){
                ans = mid;
                end = mid - 1;
            }else{
                start = mid + 1;
            }
        }

        out.println(ans);
    }

    private static HashMap<Integer, ArrayList<Integer>> getMapAccordingly(HashMap<Integer, NavigableSet<Integer>> map, int day){
        HashMap<Integer, ArrayList<Integer>> curMap = new HashMap();

        for(Integer in: map.keySet()){
            NavigableSet<Integer> set = map.get(in);
            Integer cur = set.floor(day);
            if(cur == null) continue;
            curMap.putIfAbsent(cur, new ArrayList<>());
            curMap.get(cur).add(in);
        }

//        out.println(day + " " + curMap);

        return curMap;
    }

    private static boolean OK(int days, HashMap<Integer, ArrayList<Integer>> map, int[] k, int n){
        int cur = 0;
//        out.println(days);

        for(int i = 1; i <= days; i++){
            ++cur;
            ArrayList<Integer> index = map.get(i);
            if(index == null) continue;
            for(Integer in: index){
                if(cur == 0) break;
                int min = Math.min(cur, k[in - 1]);
                cur -= min;
                k[in - 1] -= min;
            }
        }

        for(int i = 0; i < n; i++) cur -= 2 * k[i];

        return cur >= 0;
    }
}

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

public class Main {

    public static void main(String[] args) throws IOException {
        new Solver().solve();
    }

    static class Solver {
        StringBuilder sb = new StringBuilder();
        //Scanner reader = new Scanner(System.in);
        Reader reader = new Reader();
        final int MX = 400007;
        ArrayList<Integer>[] spec;
        int n, m;
        int[] need;

        void solve() throws IOException {
            n = reader.nextInt();
            m = reader.nextInt();
            spec = new ArrayList[MX];
            for(int i = 0; i < MX; ++ i) spec[i] = new ArrayList<>();
            need = new int[n];
            for(int i = 0; i < n; ++ i)
                need[i] = reader.nextInt();
            for(int i = 0; i < m; ++ i) {
                int d = reader.nextInt() - 1, t = reader.nextInt() - 1;
                spec[d].add(t);
            }
            int l = 1, r = MX;
            while(l < r) {
                int mid = (l + r) / 2;
                if(!check(mid))
                    l = mid + 1;
                else r = mid;
            }
            write(l);
            System.out.println(sb);
        }

        boolean check(int cnt) {
            int[] ava = new int[cnt + 1];
            int[] nd = need.clone();
            for(int i = 0; i <= cnt; ++ i)
                ava[i] = i + 1;
            int rem = cnt;
            for(int i = cnt - 1; i >= 0; -- i) {
                ava[i] = Math.min(ava[i], ava[i + 1]);
                for(int a : spec[i]) {
                    while(nd[a] > 0 && ava[i] > 0) {
                        -- nd[a];
                        -- ava[i];
                        -- rem;
                    }
                }
            }
            return (rem / 2 >= Arrays.stream(nd).sum());
        }

        <T> void write(T ...objects) {
            for(int i = 0; i < objects.length; ++ i)
                sb.append(objects[i]).append(' ');
        }

        <T> void writeln(T ...objects) {
            if(objects.length == 0) sb.append('\n');
            for(T object : objects)
                sb.append(object).append('\n');
        }
    }

    static class Reader {
        final private int BUFFER_SIZE = 1 << 16;private DataInputStream din;private byte[] buffer;private int bufferPointer, bytesRead;
        public Reader(){din=new DataInputStream(System.in);buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0;
        }public Reader(String file_name) throws IOException {din=new DataInputStream(new FileInputStream(file_name));buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0;
        }public String readLine() throws IOException{byte[] buf=new byte[64];int cnt=0,c;while((c=read())!=-1){if(c=='\n')break;buf[cnt++]=(byte)c;}return new String(buf,0,cnt);
        }public int nextInt() throws IOException{int ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret;
        }public long nextLong() throws IOException{long ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret;
        }public double nextDouble() throws IOException{double ret=0,div=1;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c = read();do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(c=='.')while((c=read())>='0'&&c<='9')ret+=(c-'0')/(div*=10);if(neg)return -ret;return ret;
        }private void fillBuffer() throws IOException{bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE);if(bytesRead==-1)buffer[0]=-1;
        }private byte read() throws IOException{if(bufferPointer==bytesRead)fillBuffer();return buffer[bufferPointer++];
        }public void close() throws IOException{if(din==null) return;din.close();}
    }
}

//Created by Aminul on 5/14/2019.

import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Scanner;

public class F2 {
    static int maxn = (int) 4e5 + 5;
    static int n, m, f[], sum;
    static ArrayDeque<Integer> g[];

    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(System.in);
        PrintWriter pw = new PrintWriter(System.out);

        n = in.nextInt();
        m = in.nextInt();
        f = new int[n + 1];
        g = genDQ(maxn);
        sum = 0;

        for (int i = 1; i <= n; i++) {
            int k = in.nextInt();
            f[i] = k;
            sum += k;
        }

        for (int i = 0; i < m; i++) {
            int d = in.nextInt(), t = in.nextInt();
            g[d].add(t);
        }

        int ans = binarySearch();
        pw.println(ans);

        pw.close();
    }

    static int binarySearch() {
        int lo = 0, hi = maxn, mid;
        while (lo < hi) {
            mid = (lo + hi) / 2;
            if (check(mid)) hi = mid;
            else lo = mid + 1;
        }
        if (lo > 0 && check(lo - 1)) lo--;
        return lo;
    }

    static boolean check(int x) {
        int money = x;
        int rem = 2*sum - x;
        int frq[] = f.clone();
        for (int i = x; i >= 1; i--) {
            money = Math.min(money, i);
            for (int j : g[i]) {
                while (money > 0 && frq[j] > 0) {
                    money--;
                    frq[j]--;
                    rem--;
                }
            }
        }
        return rem <= 0;
    }

    static <T> ArrayDeque<T>[] genDQ(int n) {
        ArrayDeque<T> list[] = new ArrayDeque[n];
        for (int i = 0; i < n; i++) list[i] = new ArrayDeque<T>();
        return list;
    }

    static void debug(Object... obj) {
        System.err.println(Arrays.deepToString(obj));
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.Map.Entry;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Washoum
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        inputClass in = new inputClass(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
        solver.solve(1, in, out);
        out.close();
    }

    static class F2MicrotransactionsHardVersion {
        static int n;
        static int m;
        static long sum;
        static int[] nb;
        static F2MicrotransactionsHardVersion.Pair[] promo;

        public void solve(int testNumber, inputClass sc, PrintWriter out) {
            n = sc.nextInt();
            m = sc.nextInt();
            nb = new int[n];
            sum = 0;
            for (int i = 0; i < n; i++) {
                nb[i] = sc.nextInt();
                sum += nb[i];
            }
            promo = new F2MicrotransactionsHardVersion.Pair[m];
            for (int i = 0; i < m; i++) {
                promo[i] = new F2MicrotransactionsHardVersion.Pair();
                promo[i].x = sc.nextInt();
                promo[i].y = sc.nextInt() - 1;
            }

            Arrays.sort(promo, new Comparator<F2MicrotransactionsHardVersion.Pair>() {

                public int compare(F2MicrotransactionsHardVersion.Pair a, F2MicrotransactionsHardVersion.Pair b) {
                    return Integer.compare(a.x, b.x);
                }
            });

            long l = 0;
            long r = (long) 1e18;
            long ans = 0;
            while (r - l >= 0) {
                long mid = (l + r) / 2;
                if (check(mid)) {
                    ans = mid;
                    r = mid - 1;
                } else {
                    l = mid + 1;
                }
            }
            out.println(ans);
        }

        static boolean check(long mid) {
            if (mid >= 2 * sum) {
                return true;
            }
            if (mid < sum) {
                return false;
            }
            HashMap<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < m && promo[i].x <= mid; i++) {
                map.put(promo[i].y, promo[i].x);
            }
            ArrayList<F2MicrotransactionsHardVersion.Pair> lst = new ArrayList<>();
            for (Map.Entry<Integer, Integer> entre : map.entrySet()) {
                F2MicrotransactionsHardVersion.Pair p = new F2MicrotransactionsHardVersion.Pair();
                p.x = entre.getValue();
                p.y = entre.getKey();
                lst.add(p);
            }
            lst.sort(new Comparator<F2MicrotransactionsHardVersion.Pair>() {

                public int compare(F2MicrotransactionsHardVersion.Pair a, F2MicrotransactionsHardVersion.Pair b) {
                    return Integer.compare(a.x, b.x);
                }
            });
            int[] each = new int[n];
            System.arraycopy(nb, 0, each, 0, n);
            long kadeh = 0;
            int last = 0;
            for (int i = 0; i < lst.size(); i++) {
                last = lst.get(i).x;
                if (i > 0) {
                    kadeh += lst.get(i).x - lst.get(i - 1).x;
                } else {
                    kadeh += lst.get(i).x;
                }

                if (each[lst.get(i).y] > 0) {
                    if (each[lst.get(i).y] >= kadeh) {
                        each[lst.get(i).y] -= kadeh;
                        kadeh = 0;
                    } else {
                        kadeh -= each[lst.get(i).y];
                        each[lst.get(i).y] = 0;
                    }
                }
            }
            kadeh += mid - last;
            long rem = 0;
            for (int i = 0; i < n; i++) {
                rem += each[i];
            }
            return kadeh >= rem * 2;
        }

        static class Pair {
            int x;
            int y;

        }

    }

    static class inputClass {
        BufferedReader br;
        StringTokenizer st;

        public inputClass(InputStream in) {

            br = new BufferedReader(new InputStreamReader(in));
        }

        public String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

import java.io.*;
import java.util.*;

public class tr0 {
	static PrintWriter out;
	static StringBuilder sb;
	static long mod =998244353;
    static int n,m,sum;
    static int[]a,ldays,ele;
    static pair []k;
	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner(System.in);
		out = new PrintWriter(System.out);
		n=sc.nextInt();
		m=sc.nextInt();
		a=new int[n];
		sum=0;
		for(int i=0;i<n;i++)
			sum+=a[i]=sc.nextInt();
	    k=new pair[m];
	    sum*=2;
	    ele=new int[n];
	    for(int i=0;i<m;i++) {
	            k[i]=new pair(sc.nextInt(),sc.nextInt());
	    }
	    ldays=new int [500000];
	    int lo=0;
	    int hi=sum;
	    int ans=0;
	    while(lo<=hi) {
	    	int mid=(lo+hi)/2;
	//    	out.println(mid);
	    	if(v(mid)) {
	    		hi=mid-1;
	    		ans=mid;
	    	//	out.println(mid);
	    	}
	    	else
	    		lo=mid+1;
	    }
	    out.println(ans);
		out.flush();
	}
     static boolean v(int mm) {
    	 int to=0;
    	 int money=0;
    	 ele=new int[n];
    	 for(int i=0;i<m;i++) {
    		 if(k[i].d<=mm) {
 	    	ele[k[i].t-1]=Math.max(ele[k[i].t-1],k[i].d);
    		 }
 	    }
    	 ldays=new int [500000];
 	    for(int i=0;i<n;i++) {
 	    	if(ele[i]!=0) {
 	    		ldays[ele[i]-1]+=a[i];
 	    	}
 	    }
    	 for(int i=0;i<mm;i++) {
    		 money++;
    		 if(ldays[i]!=0) {
    			 if(money>=ldays[i]) {
    				 money-=ldays[i];
    				 to+=ldays[i];
    			 }
    			 else if(money<ldays[i]) {
    				 to+=money;
    				 money=0;
    			 }
    		 }
    	 }
    	// if(mm==214)
    		// out.println("OO "+money+" "+to+" "+sum);
    	 if((sum-to*2)>money)
    		 return false;
    	 return true;
     }
	static public class segmentTree {
		int[] array, tree, lazy;
		int n;

		segmentTree(int[] aa) {
			array = aa;
			n = array.length - 1;
			tree = new int[n * 4];
			lazy = new int[n * 4];
			Arrays.fill(lazy, -1);
			build(1, 1, n);
		}

		public String toString() {
			return Arrays.toString(tree);
		}

		void build(int node, int l, int r) {
			if (l == r)
				tree[node] = array[r];
			else {
				int mid = (l + r) >> 1;
				build(node << 1, l, mid);
				build((node << 1) | 1, mid + 1, r);
				tree[node] = tree[node << 1] + tree[node << 1 | 1];
			}
		}

		void updateRange(int i, int j, int v) {
			updateR(1, 1, n, i, j, v);
		}

		void updateR(int node, int l, int r, int i, int j, int v) {
			if (i > r || j < l)
				return;
			if (i <= l && j >= r) {
				tree[node] = (r - l + 1) * v;
				lazy[node] = v;
			} else {
				int mid = l + r >> 1;
				propagate(node, l, mid, r);
				updateR(node << 1, l, mid, i, j, v);
				updateR(node << 1 | 1, mid + 1, r, i, j, v);
				tree[node] = tree[node << 1] + tree[node << 1 | 1];
			}
		}

		void propagate(int node, int b, int mid, int e) {
			if (lazy[node] != -1) {
				lazy[node << 1] = lazy[node];
				lazy[node << 1 | 1] = lazy[node];
				tree[node << 1] = (mid - b + 1) * lazy[node];
				tree[node << 1 | 1] = (e - mid) * lazy[node];
			}
			lazy[node] = -1;
		}

		int query(int i, int j) {
			return query(1, 1, n, i, j);
		}

		int query(int node, int b, int e, int i, int j) // O(log n)
		{
			if (i > e || j < b)
				return 0;
			if (b >= i && e <= j)
				return tree[node];
			int mid = b + e >> 1;
			propagate(node, b, mid, e);
			int q1 = query(node << 1, b, mid, i, j);
			int q2 = query(node << 1 | 1, mid + 1, e, i, j);
			return q1 + q2;

		}

	}

	static long fac(int n) {
		if (n == 0)
			return 1;
		if (n == 1)
			return 1;
		long ans = 1;
		for (int i = 1; i <= n; i++)
			ans = (i % mod * ans % mod) % mod;
		return ans % mod;
	}

	static long gcd(long a, long b) {

		if (b == 0)
			return a;
		return gcd(b, a % b);
	}

	static class pair implements Comparable<pair> {
		int d;
		int t;

		pair(int d,int t){
			this.d=d;
			this.t=t;
		}
		public String toString() {
			return t + " " + d;
		}

		public int compareTo(pair o) {
			return o.d - d;
		}
	}

	static class unionfind {
		int[] p;
		int[] size;

		unionfind(int n) {
			p = new int[n];
			size = new int[n];

			for (int i = 0; i < n; i++) {
				p[i] = i;
			}
			Arrays.fill(size, 1);
		}

		int findSet(int v) {
			if (v == p[v])
				return v;
			return p[v] = findSet(p[v]);
		}

		boolean sameSet(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return true;
			return false;
		}

		int max() {
			int max = 0;
			for (int i = 0; i < size.length; i++)
				if (size[i] > max)
					max = size[i];
			return max;
		}

		void combine(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return;
			if (size[a] > size[b]) {
				p[b] = a;
				size[a] += size[b];

			} else {
				p[a] = b;
				size[b] += size[a];
			}
		}
	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public String nextLine() throws IOException {
			return br.readLine();
		}

		public int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		public double nextDouble() throws IOException {
			return Double.parseDouble(next());
		}

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

		public Long nextLong() throws IOException {
			return Long.parseLong(next());
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}

import java.io.BufferedReader;
// import java.io.FileInputStream;
// import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.round;
import static java.lang.Math.sqrt;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.fill;
import static java.util.Arrays.sort;
import static java.util.Collections.reverse;
import static java.util.Collections.reverseOrder;
import static java.util.Collections.sort;
import static java.util.Comparator.comparing;
import static java.util.Comparator.comparingInt;
import static java.util.Comparator.comparingLong;

public class Main {
    FastScanner in;
    PrintWriter out;

    class Pair {
        long d;
        int t;

        Pair(long d, int t) {
            this.d = d;
            this.t = t;
        }
    }

    int n, m;
    long[] k, curK;
    Pair[] p;

    private void solve() throws IOException {
        n = in.nextInt();
        m = in.nextInt();
        k = new long[n];
        curK = new long[n];
        for (int i = 0; i < n; i++)
            k[i] = in.nextLong();

        p = new Pair[m];
        for (int i = 0; i < m; i++)
            p[i] = new Pair(in.nextLong(), in.nextInt() - 1);

        shuffle(p);
        sort(p, comparingLong(o -> o.d));

        long l = 0, r = 1_000_000;
        while (l + 1 < r) {
            long mid = (l + r) / 2;
            if (check(mid))
                r = mid;
            else
                l = mid;
        }
        out.println(r);
    }

    boolean check(long D) {
        fill(curK, 0);
        long cur = D, spec = 0, cnt;
        for (int i = m - 1; i >= 0; i--) {
            if (p[i].d > D) continue;
            if (p[i].d < cur) {
                spec += cur - p[i].d;
                cur = p[i].d;
            }
            if (curK[p[i].t] < k[p[i].t]) {
                cnt = min(k[p[i].t] - curK[p[i].t], cur);
                curK[p[i].t] += cnt;
                cur -= cnt;
            }
        }
        cnt = 0;
        for (int i = 0; i < k.length; i++)
            cnt += k[i] - curK[i];
        return cnt * 2 <= spec + cur;
    }

    void shuffle(Pair[] a) {
        Random random = new Random();
        for (int i = a.length - 1, j; i > 0; i--) {
            j = random.nextInt(i + 1);
            long swap = a[j].d;
            a[j].d = a[i].d;
            a[i].d = swap;
            int sw = a[j].t;
            a[j].t = a[i].t;
            a[i].t = sw;
        }
    }

    private void solveD() throws IOException {
        int n = in.nextInt();
        long[] d = new long[n];
        for (int i = 0; i < n; i++)
            d[i] = in.nextLong();
        shuffle(d);
        sort(d);

        ArrayList<long[]> f = new ArrayList<>();
        for (int i = 0; i < n; i++)
            f.addAll(factorize(d[i]));
        sort(f, (o1, o2) -> o1[0] != o2[0] ? Long.compare(o1[0], o2[0]) : Long.compare(o2[1], o1[1]));

        ArrayList<long[]> f2 = new ArrayList<>();
        for (int i = 0; i < f.size(); i++)
            if (i == 0 || f.get(i - 1)[0] != f.get(i)[0])
                f2.add(f.get(i));

        long cur = 0, cnt = 1;
        for (int i = f2.size() - 1; i >= 0; i--) {
            for (int j = 0; j < f2.get(i)[1]; j++) {
                cur *= f2.get(i)[0];
            }
            cnt *= f2.get(i)[1] + 1;
        }
    }

    void shuffle(long[] a) {
        Random random = new Random();
        for (int i = a.length - 1, j; i > 0; i--) {
            j = random.nextInt(i + 1);
            long swap = a[j];
            a[j] = a[i];
            a[i] = swap;
        }
    }

    void reverse(long[] a) {
        for (int i = 0, j = a.length - 1; i < j; i++, j--) {
            long swap = a[i];
            a[i] = a[j];
            a[j] = swap;
        }
    }

    ArrayList<long[]> factorize(long n) {
        ArrayList<long[]> f = new ArrayList<>();
        for (long p = 2, s; p * p <= n; p++)
            if (n % p == 0) {
                for (s = 0; n % p == 0; n /= p, s++) ;
                f.add(new long[]{p, s});
            }
        if (n > 1)
            f.add(new long[]{n, 1});
        return f;
    }

    class FastScanner {
        StringTokenizer st;
        BufferedReader br;

        FastScanner(InputStream s) {
            br = new BufferedReader(new InputStreamReader(s));
        }

        String next() throws IOException {
            while (st == null || !st.hasMoreTokens())
                st = new StringTokenizer(br.readLine());
            return st.nextToken();
        }

        boolean hasNext() throws IOException {
            return br.ready() || (st != null && st.hasMoreTokens());
        }

        int nextInt() throws IOException {
            return Integer.parseInt(next());
        }

        long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        double nextDouble() throws IOException {
            return Double.parseDouble(next());
        }

        String nextLine() throws IOException {
            return br.readLine();
        }

        boolean hasNextLine() throws IOException {
            return br.ready();
        }
    }

    private void run() throws IOException {
        in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in"));
        out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out"));

        for (int t = 1; t-- > 0; )
            solve();

        out.flush();
        out.close();
    }

    public static void main(String[] args) throws IOException {
        new Main().run();
    }
}

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.TreeSet;

public class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int m = in.nextInt();

    int[] wanted = new int[n];
    for (int i = 0; i < n; i += 1) {
      wanted[i] = in.nextInt();
    }

    Discount[] discounts = new Discount[m];
    for (int i = 0; i < m; i += 1) {
      int day = in.nextInt();
      int type = in.nextInt() - 1;
      discounts[i] = new Discount(type, day);
    }

    int res = solve(wanted, discounts);
    System.out.println(res);
  }

  private static int solve(final int[] wanted, Discount[] discounts) {
    DiscountCatalogue catalogue = new DiscountCatalogue(wanted.length);
    catalogue.add(discounts);

    int days = 0;
    int power = (1 << 25);

    while (power > 0) {
      int nextDays = days + power;
      power >>= 1;

      if (!canBuy(wanted, catalogue, nextDays)) {
        days = nextDays;
      }
    }
    return days + 1;
  }

  private static boolean canBuy(final int[] wanted, final DiscountCatalogue catalogue, int days) {
    ArrayList<Discount> discounts = new ArrayList<Discount>();
    int total = 0;

    for (int i = 0; i < wanted.length; i += 1) {
      total += wanted[i];

      int day = catalogue.lastDay(i, days);
      if (day != -1) {
        discounts.add(new Discount(i, day));
      }
    }

    Collections.sort(discounts);

    int needed = 0;
    for (Discount d : discounts) {
      int boughtAtDiscount = Math.min(wanted[d.type], d.day - needed);
      needed += boughtAtDiscount;
    }
    needed += 2 * (total - needed);

    return needed <= days;
  }
}

class DiscountCatalogue {
  private ArrayList<TreeSet<Integer>> discounts;

  public DiscountCatalogue(int size) {
    discounts = new ArrayList<TreeSet<Integer>>(size);
    for (int i = 0; i < size; i += 1) {
      discounts.add(new TreeSet<Integer>());
    }
  }

  public void add(final Discount[] discounts) {
    for (final Discount d : discounts) {
      add(d);
    }
  }

  public void add(final Discount discount) {
    discounts.get(discount.type).add(discount.day);
  }

  public int lastDay(int type, int finalDay) {
    Integer day = discounts.get(type).lower(finalDay + 1);
    return (day == null) ? -1 : day;
  }
}

class Discount implements Comparable<Discount> {
  public int type;
  public int day;

  public Discount(int type, int day) {
    this.type = type;
    this.day = day;
  }

  @Override
  public int compareTo(final Discount other) {
    return day - other.day;
  }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Scanner;
import java.util.Comparator;
import java.util.Collections;
import java.util.ArrayList;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F1MicrotransactionsEasyVersion solver = new F1MicrotransactionsEasyVersion();
        solver.solve(1, in, out);
        out.close();
    }

    static class F1MicrotransactionsEasyVersion {
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            int[] reqTrans = ScannerUtils.readIntArray(in, n);
            int sumReqTrans = 0;
            for (int val : reqTrans) {
                sumReqTrans += val;
            }

            ArrayList<Integer>[] tranTypeToSpecOfferDays = new ArrayList[n];
            for (int i = 0; i < n; i++) {
                tranTypeToSpecOfferDays[i] = new ArrayList<>();
            }

            while (m-- > 0) {
                int day = in.nextInt();
                int tranType = in.nextInt() - 1;
                tranTypeToSpecOfferDays[tranType].add(day);
            }

            for (int i = 0; i < n; i++) {
                Collections.sort(tranTypeToSpecOfferDays[i]);
            }

            int lo = 1;
            int hi = sumReqTrans * 2;
            int result = -1;
            while (lo <= hi) {
                int mid = lo + (hi - lo) / 2;

                if (canBuyAll(mid, buildTransList(reqTrans, tranTypeToSpecOfferDays, mid))) {
                    result = mid;
                    hi = mid - 1;
                } else {
                    lo = mid + 1;
                }
            }

            out.println(result);
        }

        private List<F1MicrotransactionsEasyVersion.MicroTran> buildTransList(int[] reqTrans,
                                                                              ArrayList<Integer>[] tranTypeToSpecOfferDays,
                                                                              int lastDay) {
            ArrayList<F1MicrotransactionsEasyVersion.MicroTran> list = new ArrayList<>();
            for (int tranType = 0; tranType < reqTrans.length; tranType++) {
                int bsIdx =
                        ListUtils.binarySearchFirstLessThan(tranTypeToSpecOfferDays[tranType], lastDay + 1);
                int lastSpecOfferDay = bsIdx == -1 ? -1 : tranTypeToSpecOfferDays[tranType].get(bsIdx);

                list.add(new F1MicrotransactionsEasyVersion.MicroTran(tranType + 1,
                                                                      lastSpecOfferDay,
                                                                      reqTrans[tranType]));
            }
            return list;
        }

        private boolean canBuyAll(int moneyOnEndDay, List<F1MicrotransactionsEasyVersion.MicroTran> transList) {
            transList.sort(Comparator.comparingInt(mt -> mt.lastSpecOfferDay));

            int moneySpentForSpecOffers = 0;
            int transCountForLastDay = 0;
            for (F1MicrotransactionsEasyVersion.MicroTran tran : transList) {
                if (tran.lastSpecOfferDay == -1) {
                    transCountForLastDay += tran.requiredCount;
                } else {
                    int nowMoney = tran.lastSpecOfferDay - moneySpentForSpecOffers;
                    int buyCount = Math.min(nowMoney, tran.requiredCount);
                    moneySpentForSpecOffers += buyCount;
                    transCountForLastDay += tran.requiredCount - buyCount;
                }
            }

            return moneyOnEndDay - moneySpentForSpecOffers - transCountForLastDay * 2 >= 0;
        }

        private static class MicroTran {
            private final int lastSpecOfferDay;
            private final int requiredCount;
            private final int type;

            public MicroTran(int type, int lastSpecOfferDay, int requiredCount) {
                this.lastSpecOfferDay = lastSpecOfferDay;
                this.requiredCount = requiredCount;
                this.type = type;
            }

        }

    }

    static class ScannerUtils {
        public static int[] readIntArray(Scanner in, int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++) {
                array[i] = in.nextInt();
            }
            return array;
        }

    }

    static class ListUtils {
        public static <T extends Comparable<T>> int binarySearchFirstLessThan(List<T> list, T target) {
            int result = -1;
            int lo = 0;
            int hi = list.size() - 1;
            while (lo <= hi) {
                int mid = lo + (hi - lo) / 2;
                int cmpRes = list.get(mid).compareTo(target);
                if (cmpRes < 0) {
                    result = mid;
                    lo = mid + 1;
                } else {
                    hi = mid - 1;
                }
            }
            return result;
        }

    }
}

import java.io.*;
import java.util.*;

public class CF1165F2 {
	static int search(int[] dd, int d) {
		int lower = -1, upper = dd.length;
		while (upper - lower > 1) {
			int i = (lower + upper) / 2;
			if (dd[i] <= d)
				lower = i;
			else
				upper = i;
		}
		return lower == -1 ? 0 : dd[lower];
	}
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		int n = Integer.parseInt(st.nextToken());
		int m = Integer.parseInt(st.nextToken());
		st = new StringTokenizer(br.readLine());
		int[] kk = new int[n];
		int ksum = 0;
		for (int i = 0; i < n; i++)
			ksum += kk[i] = Integer.parseInt(st.nextToken());
		ArrayList[] ll = new ArrayList[n];
		for (int i = 0; i < n; i++)
			ll[i] = new ArrayList<Integer>();
		for (int j = 0; j < m; j++) {
			st = new StringTokenizer(br.readLine());
			int d = Integer.parseInt(st.nextToken());
			int i = Integer.parseInt(st.nextToken()) - 1;
			ll[i].add(d);
		}
		int[][] dd = new int[n][];
		for (int i = 0; i < n; i++) {
			ArrayList<Integer> l = ll[i];
			Collections.sort(l);
			m = l.size();
			dd[i] = new int[m];
			m = 0;
			for (int d : l)
				dd[i][m++] = d;
		}
		Integer[] ii = new Integer[n];
		for (int i = 0; i < n; i++)
			ii[i] = i;
		int[] dos = new int[n];
		int lower = 0, upper = ksum * 2;
		while (upper - lower > 1) {
			int d = (lower + upper) / 2;
			for (int i = 0; i < n; i++)
				dos[i] = search(dd[i], d);
			Arrays.sort(ii, (i, j) -> dos[i] - dos[j]);
			int savings = 0;
			for (int h = 0; h < n; h++) {
				int i = ii[h];
				savings += Math.min(dos[i] - savings, kk[i]);
			}
			if (d + savings >= ksum * 2)
				upper = d;
			else
				lower = d;
		}
		System.out.println(upper);
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Vadim
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastScanner in = new FastScanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        r560F solver = new r560F();
        solver.solve(1, in, out);
        out.close();
    }

    static class r560F {
        private int binarySearch(Sale[] sales, int day) {
            int left = 0, right = sales.length;
            while (left < right) {
                int mid = (left + right) / 2;
                if (sales[mid].d <= day) {
                    left = mid + 1;
                } else {
                    right = mid;
                }
            }
            return left - 1;
        }

        public void solve(int testNumber, FastScanner in, PrintWriter out) {
            int N = in.ni(), M = in.ni();
            int[] k = in.na(N);
            Sale[] sales = new Sale[M];
            for (int i = 0; i < M; i++) {
                sales[i] = new Sale(in.ni(), in.ni() - 1, i);
            }
            Arrays.sort(sales, (x, y) -> {
                if (x.d == y.d)
                    return Integer.compare(x.id, y.id);
                else return Integer.compare(x.d, y.d);
            });
            int left = 0, right = 400_005;
            int[] krem = new int[N];
            while (left < right) {
                int mid = (left + right) / 2;
                int from = binarySearch(sales, mid);
                System.arraycopy(k, 0, krem, 0, N);
                int rem = mid;
                int spent = 0;
//            System.out.println("mid = " + mid);
                for (int i = from; i >= 0 && rem > 0; --i) {
                    Sale sale = sales[i];
                    rem = Math.min(rem, sale.d);
                    if (krem[sale.t] > 0) {
                        int available = Math.min(rem, krem[sale.t]);
                        rem -= available;
                        spent += available;
                        krem[sale.t] -= available;
                    }
                }
                rem = mid - spent;
//            System.out.println("rem = " + rem);
//            System.out.println("Arrays.toString(krem) = " + Arrays.toString(krem));
                boolean correct = true;
                for (int i = 0; i < N && rem >= 0; i++) {
                    if (krem[i] > 0) {
                        rem -= krem[i] * 2;
                    }
                }
//            System.out.println("final rem = " + rem);
                if (rem < 0)
                    correct = false;

                if (!correct) {
                    left = mid + 1;
                } else {
                    right = mid;
                }
            }
            out.println(left);
        }

        class Sale {
            int d;
            int t;
            int id;

            public Sale(int d, int t, int id) {
                this.d = d;
                this.t = t;
                this.id = id;
            }

        }

    }

    static class FastScanner {
        private BufferedReader in;
        private StringTokenizer st;

        public FastScanner(InputStream stream) {
            in = new BufferedReader(new InputStreamReader(stream));
        }

        public String ns() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    String rl = in.readLine();
                    if (rl == null) {
                        return null;
                    }
                    st = new StringTokenizer(rl);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return st.nextToken();
        }

        public int ni() {
            return Integer.parseInt(ns());
        }

        public int[] na(int n) {
            int[] ret = new int[n];
            for (int i = 0; i < n; i++) {
                ret[i] = ni();
            }
            return ret;
        }

    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;

public class Main {

    public static void main(String[] args) throws IOException {
        StreamTokenizer streamTokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        streamTokenizer.nextToken();
        int n = (int) streamTokenizer.nval;
        streamTokenizer.nextToken();
        int m = (int) streamTokenizer.nval;

        int[] a = new int[n + 1];
        int count = 0;
        for (int i = 1; i <= n; i++) {
            streamTokenizer.nextToken();
            a[i] = (int) streamTokenizer.nval;
            count += a[i];
        }

        int[] b = new int[m + 1];
        int[] c = new int[m + 1];
        for (int i = 1; i <= m; i++) {
            streamTokenizer.nextToken();
            b[i] = (int) streamTokenizer.nval;
            streamTokenizer.nextToken();
            c[i] = (int) streamTokenizer.nval;
        }

        quickSort(b, c, 1, m);

        int[] d = new int[n + 1];

        int min = count, max = count * 2, mid, result = 0;
        int money, consume, consumeCount, index;
        while (min <= max) {
            mid = (min + max) / 2;
            consumeCount = 0;
            money = mid;
            for (index = 1; index <= m && b[index] > mid; index++) ;
            for (int i = 1; i <= n; i++)
                d[i] = a[i];
            for (; index <= m; index++) {
                money = Math.min(money, b[index]);
                consume = Math.min(d[c[index]], money);
                money -= consume;
                d[c[index]] -=consume;
                consumeCount += consume;
            }
            if (mid - consumeCount >= (count - consumeCount) * 2) {
                result = mid;
                max = mid - 1;
            } else {
                min = mid + 1;
            }
        }
        System.out.println(result);
    }

    public static void quickSort(int[] a, int[] b, int l, int r) {
        int mid = a[(l + r) / 2], temp;
        int x = l, y = r;
        while (x <= y) {
            while (x <= y && a[x] > mid) x++;
            while (y >= x && a[y] < mid) y--;
            if (x <= y) {
                temp = a[x];
                a[x] = a[y];
                a[y] = temp;
                temp = b[x];
                b[x] = b[y];
                b[y] = temp;
                x++;
                y--;
            }
        }
        if (x < r)
            quickSort(a, b, x, r);
        if (y > l)
            quickSort(a, b, l, y);
    }

}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {

    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F1MikrotranzakciiUproshennayaVersiya solver = new F1MikrotranzakciiUproshennayaVersiya();
        solver.solve(1, in, out);
        out.close();
    }

    static class F1MikrotranzakciiUproshennayaVersiya {

        int[] a;
        List<Item> items;
        int sum;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            a = new int[n];
            sum = 0;
            for (int i = 0; i < n; i++) {
                a[i] = in.nextInt();
                sum += a[i];
            }

            items = new ArrayList<>();
            for (int i = 0; i < m; i++) {
                items.add(new Item(in.nextInt(), in.nextInt() - 1));
            }
            items.sort(Comparator.comparingInt(x -> x.day));

            int[] last = new int[n];
            Arrays.fill(last, -1);
            for (int i = m - 1; i >= 0; i--) {
                Item item = items.get(i);
                if (last[item.game] != -1) {
                    item.nextDay = last[item.game];
                }
                last[item.game] = item.day;
            }

            int t1 = 0;
            int t2 = (int) 4e5 + 1;
            while (t1 < t2) {
                int mid = (t1 + t2) / 2;
                if (isPossible(mid)) {
                    t2 = mid;
                } else {
                    t1 = mid + 1;
                }
            }
            out.println(t1);
        }

        private boolean isPossible(int until) {
            int idx = 0;
            int lastStop = 0;
            int money = 0;
            int taken = 0;
            while (idx < items.size() && items.get(idx).day <= until) {
                Item item = items.get(idx);
                if (item.nextDay <= until) {
                    idx++;
                    continue;
                }
                money += item.day - lastStop;
                lastStop = item.day;
                int toTake = Math.min(money, a[item.game]);
                taken += toTake;
                money -= toTake;
                idx++;
            }
            money += until - lastStop;
            return (sum - taken) * 2 <= money;
        }

        class Item {

            int day;
            int game;
            int nextDay = (int) 1e6;

            public Item(int day, int game) {
                this.day = day;
                this.game = game;
            }
        }
    }

    static class InputReader {

        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
    static int inf = (int) 1e9 + 7;

    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        pw = new PrintWriter(System.out);
        int n = nextInt();
        int m = nextInt();
        long a[] = new long [n];
        sale b[] = new sale[m];
        for(int i = 0;i < n;i++) a[i] = nextInt();
        for(int i = 0;i < m;i++) b[i] = new sale(nextInt(), nextInt() - 1);
        Arrays.sort(b, new sale());
        long l = 0;
        long r = 100000000000l;
        long a_[] = new long [n];
        for(int i = 0;i < n;i++) a_[i] = a[i];
        while(l != r - 1) {
            long mid = (l + r) / 2;
            long cnt1 = mid;
            long cnt2 = 0;
            int id = m - 1;
            while(id >= 0 && b[id].d > mid) {
                id--;
            }
            while(id >= 0) {
                if (cnt1 > b[id].d) {
                    cnt2 += cnt1 - b[id].d;
                    cnt1 = b[id].d;
                }
                long u = Math.min(a[b[id].t], cnt1);
                a[b[id].t] -= u;
                cnt1 -= u;
                id--;
            }
            cnt2 += cnt1;
            boolean can = true;
            for(int i = 0;i < n;i++) {
                if (a[i] * 2 > cnt2) can = false;
                cnt2 -= a[i] * 2;
                a[i] = 0;
            }
            for(int i = 0;i < n;i++) a[i] = a_[i];
            if (can) r = mid;
            else l = mid;
        }
        pw.print(r);
        pw.close();
    }

    static BufferedReader br;
    static StringTokenizer st = new StringTokenizer("");
    static PrintWriter pw;

    static String next() throws IOException {
        while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static long nextLong() throws IOException {
        return Long.parseLong(next());
    }
}
class sale implements Comparator<sale>{
    long d; int t;
    sale(long d, int t) {
        this.d = d;
        this.t = t;
    }
    sale() {}

    @Override
    public int compare(sale o1, sale o2) {
        return Long.compare(o1.d, o2.d);
    }
}

import java.io.*;
import java.util.*;

public class Codechef {

    static class MyScanner{
        BufferedReader br;
	StringTokenizer st;

	MyScanner(FileReader fileReader){
            br = new BufferedReader(fileReader);
	}

	MyScanner(){
            br = new BufferedReader(new InputStreamReader(System.in));
	}

	String nn(){
            while(st == null || !st.hasMoreElements()){
		try{
                    st = new StringTokenizer(br.readLine());
		}catch(IOException e){
                    e.printStackTrace();
		}
            }
            return st.nextToken();
	}

	char nc(){
            return nn().charAt(0);
	}

	int ni(){
            return Integer.parseInt(nn());
	}

	long nl(){
            return Long.parseLong(nn());
	}

	double nd(){
            return Double.parseDouble(nn());
	}

	int[] niArr0(int n){
            int[] ar = new int[n];
            for(int i = 0; i < n; i++) ar[i] = ni();
            return ar;
	}

        int[] niArr1(int n){
            int[] ar = new int[n + 1];
            for(int i = 1; i <= n; i++) ar[i] = ni();
            return ar;
	}

        long[] nlArr0(int n){
            long[] ar = new long[n];
            for(int i = 0; i < n; i++) ar[i] = nl();
            return ar;
        }

        long[] nlArr1(int n){
            long[] ar = new long[n + 1];
            for(int i = 1; i <= n; i++) ar[i] = nl();
            return ar;
        }
    }

    public static <T> void mprintln(T ... ar){
        for(T i: ar) out.print(i + " ");
        out.println();
    }

    private static PrintWriter out;

    public static void main(String[] args) throws FileNotFoundException{

        // Input from file
        // File inputFile = new File("JavaFile.txt");
        // File outputFile = new File("JavaOutputFile.txt");
        // FileReader fileReader = new FileReader(inputFile);
        // Here it ends

        MyScanner sc = new MyScanner();
        // MyScanner sc = new MyScanner(fileReader);

        out = new PrintWriter(new BufferedOutputStream(System.out)); // Output to console
        // out = new PrintWriter(new PrintStream(outputFile)); // Output to file

        getAns(sc);

        out.close();
    }

    private static void getAns(MyScanner sc){
        int n = sc.ni(), m = sc.ni();
        int[] k = sc.niArr0(n);
        HashMap<Integer, NavigableSet<Integer>> map = new HashMap();

        for(int i = 0; i < m; i++){
            int day = sc.ni(), type = sc.ni();
            map.putIfAbsent(type, new TreeSet());
            map.get(type).add(day);
        }

//        out.println(map);

        int start = 1, end = 4 * (int)1e5;
        int ans = end;

//        out.println(map);

        while(start <= end){
            int mid = start + end >> 1;
            if(OK(mid, getMapAccordingly(map, mid), Arrays.copyOf(k, n), n)){
                ans = mid;
                end = mid - 1;
            }else{
                start = mid + 1;
            }
        }

        out.println(ans);
    }

    private static HashMap<Integer, ArrayList<Integer>> getMapAccordingly(HashMap<Integer, NavigableSet<Integer>> map, int day){
        HashMap<Integer, ArrayList<Integer>> curMap = new HashMap();

        for(Integer in: map.keySet()){
            NavigableSet<Integer> set = map.get(in);
            Integer cur = set.floor(day);
            if(cur == null) continue;
            curMap.putIfAbsent(cur, new ArrayList<>());
            curMap.get(cur).add(in);
        }

//        out.println(day + " " + curMap);

        return curMap;
    }

    private static boolean OK(int days, HashMap<Integer, ArrayList<Integer>> map, int[] k, int n){
        int cur = 0;
//        out.println(days);

        for(int i = 1; i <= days; i++){
            ++cur;
            ArrayList<Integer> index = map.get(i);
            if(index == null) continue;
            for(Integer in: index){
                if(cur == 0) break;
                int min = Math.min(cur, k[in - 1]);
                cur -= min;
                k[in - 1] -= min;
            }
        }

        for(int i = 0; i < n; i++) cur -= 2 * k[i];

        return cur >= 0;
    }
}

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

public class Main {

    public static void main(String[] args) throws IOException {
        new Solver().solve();
    }

    static class Solver {
        StringBuilder sb = new StringBuilder();
        //Scanner reader = new Scanner(System.in);
        Reader reader = new Reader();
        final int MX = 400007;
        ArrayList<Integer>[] spec;
        int n, m;
        int[] need;

        void solve() throws IOException {
            n = reader.nextInt();
            m = reader.nextInt();
            spec = new ArrayList[MX];
            for(int i = 0; i < MX; ++ i) spec[i] = new ArrayList<>();
            need = new int[n];
            for(int i = 0; i < n; ++ i)
                need[i] = reader.nextInt();
            for(int i = 0; i < m; ++ i) {
                int d = reader.nextInt() - 1, t = reader.nextInt() - 1;
                spec[d].add(t);
            }
            int l = 1, r = MX;
            while(l < r) {
                int mid = (l + r) / 2;
                if(!check(mid))
                    l = mid + 1;
                else r = mid;
            }
            write(l);
            System.out.println(sb);
        }

        boolean check(int cnt) {
            int[] ava = new int[cnt + 1];
            int[] nd = need.clone();
            for(int i = 0; i <= cnt; ++ i)
                ava[i] = i + 1;
            int rem = cnt;
            for(int i = cnt - 1; i >= 0; -- i) {
                ava[i] = Math.min(ava[i], ava[i + 1]);
                for(int a : spec[i]) {
                    while(nd[a] > 0 && ava[i] > 0) {
                        -- nd[a];
                        -- ava[i];
                        -- rem;
                    }
                }
            }
            return (rem / 2 >= Arrays.stream(nd).sum());
        }

        <T> void write(T ...objects) {
            for(int i = 0; i < objects.length; ++ i)
                sb.append(objects[i]).append(' ');
        }

        <T> void writeln(T ...objects) {
            if(objects.length == 0) sb.append('\n');
            for(T object : objects)
                sb.append(object).append('\n');
        }
    }

    static class Reader {
        final private int BUFFER_SIZE = 1 << 16;private DataInputStream din;private byte[] buffer;private int bufferPointer, bytesRead;
        public Reader(){din=new DataInputStream(System.in);buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0;
        }public Reader(String file_name) throws IOException {din=new DataInputStream(new FileInputStream(file_name));buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0;
        }public String readLine() throws IOException{byte[] buf=new byte[64];int cnt=0,c;while((c=read())!=-1){if(c=='\n')break;buf[cnt++]=(byte)c;}return new String(buf,0,cnt);
        }public int nextInt() throws IOException{int ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret;
        }public long nextLong() throws IOException{long ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret;
        }public double nextDouble() throws IOException{double ret=0,div=1;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c = read();do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(c=='.')while((c=read())>='0'&&c<='9')ret+=(c-'0')/(div*=10);if(neg)return -ret;return ret;
        }private void fillBuffer() throws IOException{bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE);if(bytesRead==-1)buffer[0]=-1;
        }private byte read() throws IOException{if(bufferPointer==bytesRead)fillBuffer();return buffer[bufferPointer++];
        }public void close() throws IOException{if(din==null) return;din.close();}
    }
}

//Created by Aminul on 5/14/2019.

import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Scanner;

public class F2 {
    static int maxn = (int) 4e5 + 5;
    static int n, m, f[], sum;
    static ArrayDeque<Integer> g[];

    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(System.in);
        PrintWriter pw = new PrintWriter(System.out);

        n = in.nextInt();
        m = in.nextInt();
        f = new int[n + 1];
        g = genDQ(maxn);
        sum = 0;

        for (int i = 1; i <= n; i++) {
            int k = in.nextInt();
            f[i] = k;
            sum += k;
        }

        for (int i = 0; i < m; i++) {
            int d = in.nextInt(), t = in.nextInt();
            g[d].add(t);
        }

        int ans = binarySearch();
        pw.println(ans);

        pw.close();
    }

    static int binarySearch() {
        int lo = 0, hi = maxn, mid;
        while (lo < hi) {
            mid = (lo + hi) / 2;
            if (check(mid)) hi = mid;
            else lo = mid + 1;
        }
        if (lo > 0 && check(lo - 1)) lo--;
        return lo;
    }

    static boolean check(int x) {
        int money = x;
        int rem = 2*sum - x;
        int frq[] = f.clone();
        for (int i = x; i >= 1; i--) {
            money = Math.min(money, i);
            for (int j : g[i]) {
                while (money > 0 && frq[j] > 0) {
                    money--;
                    frq[j]--;
                    rem--;
                }
            }
        }
        return rem <= 0;
    }

    static <T> ArrayDeque<T>[] genDQ(int n) {
        ArrayDeque<T> list[] = new ArrayDeque[n];
        for (int i = 0; i < n; i++) list[i] = new ArrayDeque<T>();
        return list;
    }

    static void debug(Object... obj) {
        System.err.println(Arrays.deepToString(obj));
    }
}

//Created by Aminul on 5/14/2019.

import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Scanner;

public class F2_1 {
    static int maxn = (int) 4e5 + 5;
    static int n, m, f[], sum;
    static ArrayDeque<Integer> g[];

    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(System.in);
        PrintWriter pw = new PrintWriter(System.out);

        n = in.nextInt();
        m = in.nextInt();
        f = new int[n + 1];
        g = genDQ(maxn);
        sum = 0;

        for (int i = 1; i <= n; i++) {
            int k = in.nextInt();
            f[i] = k;
            sum += k;
        }

        for (int i = 0; i < m; i++) {
            int d = in.nextInt(), t = in.nextInt();
            g[d].add(t);
        }

        int ans = binarySearch();
        pw.println(ans);

        pw.close();
    }

    static int binarySearch() {
        int lo = 0, hi = maxn, mid;
        while (lo < hi) {
            mid = (lo + hi) / 2;
            if (check(mid)) hi = mid;
            else lo = mid + 1;
        }
        if (lo > 0 && check(lo - 1)) lo--;
        return lo;
    }

    static boolean check(int x) {
        int money = x, saved = 0;
        int rem = sum;
        int frq[] = f.clone();
        for (int i = x; i >= 1; i--) {
            if (money + saved >= 2 * rem) return true;
            while (money > i) {
                money--;
                saved++;
            }
            for (int j : g[i]) {
                while (money > 0 && frq[j] > 0) {
                    money--;
                    frq[j]--;
                    rem--;
                    if (money + saved >= 2 * rem) return true;
                }
            }
            if (money + saved >= 2 * rem) return true;
        }
        return false;
    }

    static <T> ArrayDeque<T>[] genDQ(int n) {
        ArrayDeque<T> list[] = new ArrayDeque[n];
        for (int i = 0; i < n; i++) list[i] = new ArrayDeque<T>();
        return list;
    }

    static void debug(Object... obj) {
        System.err.println(Arrays.deepToString(obj));
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.Map.Entry;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Washoum
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        inputClass in = new inputClass(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
        solver.solve(1, in, out);
        out.close();
    }

    static class F2MicrotransactionsHardVersion {
        static int n;
        static int m;
        static long sum;
        static int[] nb;
        static F2MicrotransactionsHardVersion.Pair[] promo;

        public void solve(int testNumber, inputClass sc, PrintWriter out) {
            n = sc.nextInt();
            m = sc.nextInt();
            nb = new int[n];
            sum = 0;
            for (int i = 0; i < n; i++) {
                nb[i] = sc.nextInt();
                sum += nb[i];
            }
            promo = new F2MicrotransactionsHardVersion.Pair[m];
            for (int i = 0; i < m; i++) {
                promo[i] = new F2MicrotransactionsHardVersion.Pair();
                promo[i].x = sc.nextInt();
                promo[i].y = sc.nextInt() - 1;
            }

            Arrays.sort(promo, Comparator.comparingInt(a -> a.x));

            long l = 0;
            long r = (long) 1e6;
            long ans = 0;
            while (r - l >= 0) {
                long mid = (l + r) / 2;
                if (check(mid)) {
                    ans = mid;
                    r = mid - 1;
                } else {
                    l = mid + 1;
                }
            }
            out.println(ans);
        }

        static boolean check(long mid) {
            if (mid >= 2 * sum) {
                return true;
            }
            if (mid < sum) {
                return false;
            }
            HashMap<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < m && promo[i].x <= mid; i++) {
                map.put(promo[i].y, promo[i].x);
            }
            ArrayList<F2MicrotransactionsHardVersion.Pair> lst = new ArrayList<>();
            for (Map.Entry<Integer, Integer> entre : map.entrySet()) {
                F2MicrotransactionsHardVersion.Pair p = new F2MicrotransactionsHardVersion.Pair();
                p.x = entre.getValue();
                p.y = entre.getKey();
                lst.add(p);
            }
            lst.sort(Comparator.comparingInt(a -> a.x));
            int[] each = new int[n];
            System.arraycopy(nb, 0, each, 0, n);
            long kadeh = 0;
            int last = 0;
            for (int i = 0; i < lst.size(); i++) {
                last = lst.get(i).x;
                if (i > 0) {
                    kadeh += lst.get(i).x - lst.get(i - 1).x;
                } else {
                    kadeh += lst.get(i).x;
                }

                if (each[lst.get(i).y] > 0) {
                    if (each[lst.get(i).y] >= kadeh) {
                        each[lst.get(i).y] -= kadeh;
                        kadeh = 0;
                    } else {
                        kadeh -= each[lst.get(i).y];
                        each[lst.get(i).y] = 0;
                    }
                }
            }
            kadeh += mid - last;
            long rem = 0;
            for (int i = 0; i < n; i++) {
                rem += each[i];
            }
            return kadeh >= rem * 2;
        }

        static class Pair {
            int x;
            int y;

        }

    }

    static class inputClass {
        BufferedReader br;
        StringTokenizer st;

        public inputClass(InputStream in) {

            br = new BufferedReader(new InputStreamReader(in));
        }

        public String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.Map.Entry;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Washoum
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        inputClass in = new inputClass(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
        solver.solve(1, in, out);
        out.close();
    }

    static class F2MicrotransactionsHardVersion {
        static int n;
        static int m;
        static long sum;
        static int[] nb;
        static F2MicrotransactionsHardVersion.Pair[] promo;

        public void solve(int testNumber, inputClass sc, PrintWriter out) {
            n = sc.nextInt();
            m = sc.nextInt();
            nb = new int[n];
            sum = 0;
            for (int i = 0; i < n; i++) {
                nb[i] = sc.nextInt();
                sum += nb[i];
            }
            promo = new F2MicrotransactionsHardVersion.Pair[m];
            for (int i = 0; i < m; i++) {
                promo[i] = new F2MicrotransactionsHardVersion.Pair();
                promo[i].x = sc.nextInt();
                promo[i].y = sc.nextInt() - 1;
            }

            Arrays.sort(promo, new Comparator<F2MicrotransactionsHardVersion.Pair>() {

                public int compare(F2MicrotransactionsHardVersion.Pair a, F2MicrotransactionsHardVersion.Pair b) {
                    return Integer.compare(a.x, b.x);
                }
            });

            long l = 0;
            long r = (long) 1e18;
            long ans = 0;
            while (r - l >= 0) {
                long mid = (l + r) / 2;
                if (check(mid)) {
                    ans = mid;
                    r = mid - 1;
                } else {
                    l = mid + 1;
                }
            }
            out.println(ans);
        }

        static boolean check(long mid) {
            if (mid >= 2 * sum) {
                return true;
            }
            if (mid < sum) {
                return false;
            }
            HashMap<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < m && promo[i].x <= mid; i++) {
                map.put(promo[i].y, promo[i].x);
            }
            ArrayList<F2MicrotransactionsHardVersion.Pair> lst = new ArrayList<>();
            for (Map.Entry<Integer, Integer> entre : map.entrySet()) {
                F2MicrotransactionsHardVersion.Pair p = new F2MicrotransactionsHardVersion.Pair();
                p.x = entre.getValue();
                p.y = entre.getKey();
                lst.add(p);
            }
            lst.sort(new Comparator<F2MicrotransactionsHardVersion.Pair>() {

                public int compare(F2MicrotransactionsHardVersion.Pair a, F2MicrotransactionsHardVersion.Pair b) {
                    return Integer.compare(a.x, b.x);
                }
            });
            int[] each = new int[n];
            System.arraycopy(nb, 0, each, 0, n);
            long kadeh = 0;
            int last = 0;
            for (int i = 0; i < lst.size(); i++) {
                last = lst.get(i).x;
                if (i > 0) {
                    kadeh += lst.get(i).x - lst.get(i - 1).x;
                } else {
                    kadeh += lst.get(i).x;
                }

                if (each[lst.get(i).y] > 0) {
                    if (each[lst.get(i).y] >= kadeh) {
                        each[lst.get(i).y] -= kadeh;
                        kadeh = 0;
                    } else {
                        kadeh -= each[lst.get(i).y];
                        each[lst.get(i).y] = 0;
                    }
                }
            }
            kadeh += mid - last;
            long rem = 0;
            for (int i = 0; i < n; i++) {
                rem += each[i];
            }
            return kadeh >= rem * 2;
        }

        static class Pair {
            int x;
            int y;

        }

    }

    static class inputClass {
        BufferedReader br;
        StringTokenizer st;

        public inputClass(InputStream in) {

            br = new BufferedReader(new InputStreamReader(in));
        }

        public String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

import java.util.*;
import java.io.*;
import java.text.*;
public class Main{
    //SOLUTION BEGIN
    //This code is not meant for understanding, you have been warned.
    void pre() throws Exception{}
    void solve(int TC) throws Exception{
        int n = ni(), m = ni();
        long[] count = new long[n];
        for(int i = 0; i< n; i++)count[i] = ni();
        HashSet<Integer>[] offer = new HashSet[MX];TreeSet<Integer>[] roffer = new TreeSet[MX];
        for(int i = 0; i< MX; i++){offer[i] = new HashSet<>();roffer[i] = new TreeSet<>();}
        for(int i = 0; i< m; i++){
            int d = ni(), t = ni()-1;
            offer[d].add(t);
            roffer[t].add(d);
        }
        int lo = 0, hi = MX;
        while(lo+1<hi){
            int mid = lo+(hi-lo)/2;
            if(check(count, offer, roffer, mid))hi = mid;
            else lo = mid;
        }
        if(check(count,offer, roffer,lo))hi = lo;
        pn(hi);
    }
    boolean check(long[] cnt, HashSet<Integer>[] offer, TreeSet<Integer>[] roffer, int day){
        long[] count = Arrays.copyOfRange(cnt, 0, cnt.length);
        long coin = 0, rem = 0;
        for(int cur = 1; cur<= day; cur++){
            coin++;
            for(int x:offer[cur]){
                if(roffer[x].floor(day)!=cur)continue;
                long mn = Math.min(coin, count[x]);
                count[x] -= mn;
                coin-=mn;
            }
        }
        for(long i:count)rem+=2*i;
        return coin>=rem;
    }
    //SOLUTION END
    void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
    long mod = (long)998244353, IINF = (long)1e18;
    final int INF = (int)1e9, MX = (int)5e5+1;
    DecimalFormat df = new DecimalFormat("0.00000000000");
    double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8;
    static boolean multipleTC = false, memory = false;
    FastReader in;PrintWriter out;
    void run() throws Exception{
        in = new FastReader();
        out = new PrintWriter(System.out);
        //Solution Credits: Taranpreet Singh
        int T = (multipleTC)?ni():1;
        pre();for(int t = 1; t<= T; t++)solve(t);
        out.flush();
        out.close();
    }
    public static void main(String[] args) throws Exception{
        if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
        else new Main().run();
    }
    long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
    int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
    int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
    void p(Object o){out.print(o);}
    void pn(Object o){out.println(o);}
    void pni(Object o){out.println(o);out.flush();}
    String n()throws Exception{return in.next();}
    String nln()throws Exception{return in.nextLine();}
    int ni()throws Exception{return Integer.parseInt(in.next());}
    long nl()throws Exception{return Long.parseLong(in.next());}
    double nd()throws Exception{return Double.parseDouble(in.next());}

    class FastReader{
        BufferedReader br;
        StringTokenizer st;
        public FastReader(){
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public FastReader(String s) throws Exception{
            br = new BufferedReader(new FileReader(s));
        }

        String next() throws Exception{
            while (st == null || !st.hasMoreElements()){
                try{
                    st = new StringTokenizer(br.readLine());
                }catch (IOException  e){
                    throw new Exception(e.toString());
                }
            }
            return st.nextToken();
        }

        String nextLine() throws Exception{
            String str = "";
            try{
                str = br.readLine();
            }catch (IOException e){
                throw new Exception(e.toString());
            }
            return str;
        }
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Collections;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author beginner1010
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskF2 solver = new TaskF2();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskF2 {
        boolean can(int days, ArrayList<Sale> allSales, int[] required) {
            ArrayList<Sale> sales = new ArrayList<>();
            boolean[] seenType = new boolean[required.length];
            for (int i = allSales.size() - 1; i >= 0; i--) {
                if (seenType[allSales.get(i).type] || allSales.get(i).day > days)
                    continue;
                seenType[allSales.get(i).type] = true;
                sales.add(new Sale(allSales.get(i).day, allSales.get(i).type));
            }

            Collections.reverse(sales);
            int sum = 0;
            for (int i = 0; i < required.length; i++) {
                sum += required[i];
            }

            int burles = 0;
            int lastDay = 0;
            for (int i = 0; i < sales.size(); i++) {
                int day = sales.get(i).day;
                int type = sales.get(i).type;
                burles += day - lastDay;
                int discount = Math.min(required[type], burles);
                burles -= discount;
                sum -= discount;
                lastDay = sales.get(i).day;
            }
            burles += days - lastDay;
            return sum * 2 <= burles;
        }

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            int[] required = new int[n];
            for (int i = 0; i < n; i++) {
                required[i] = in.nextInt();
            }

            ArrayList<Sale> allSales = new ArrayList<>();
            for (int i = 0; i < m; i++) {
                int day = in.nextInt();
                int type = in.nextInt() - 1;
                allSales.add(new Sale(day, type));
            }
            Collections.sort(allSales);

            int lo = 0;
            int hi = (int) (4e5 + 5);
            while (lo < hi) {
                int mid = (lo + hi) >> 1;
                if (can(mid, allSales, required) == true) {
                    hi = mid;
                } else {
                    lo = mid + 1;
                }
            }
            out.println(lo);
        }

        class Sale implements Comparable<Sale> {
            int day;
            int type;

            Sale(int day, int type) {
                this.day = day;
                this.type = type;
            }

            public int compareTo(Sale o) {
                if (this.day != o.day) return this.day < o.day ? -1 : 1;
                if (this.type != o.type) return this.type < o.type ? -1 : 1;
                return 0;
            }

        }

    }

    static class InputReader {
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputStream stream;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        private boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isWhitespace(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isWhitespace(c));
            return res * sgn;
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Comparator;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Jeel Vaishnav
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
        solver.solve(1, in, out);
        out.close();
    }

    static class F2MicrotransactionsHardVersion {
        public void solve(int testNumber, InputReader sc, PrintWriter out) {
            int n = sc.nextInt();
            int m = sc.nextInt();

            long totcnt = 0;

            long k[] = new long[n];
            for (int i = 0; i < n; ++i) {
                k[i] = sc.nextLong();
                totcnt += k[i];
            }

            Pair p[] = new Pair[m];
            for (int i = 0; i < m; ++i) {
                p[i] = new Pair(sc.nextInt(), sc.nextInt() - 1);
            }

            Arrays.sort(p, new Comparator<Pair>() {

                public int compare(Pair o1, Pair o2) {
                    return o2.day - o1.day;
                }
            });

            long start = 0, end = (long) 1e11, ans = (long) 1e11;
            while (start <= end) {
                long mid = (start + end) >> 1;

                long req[] = new long[n];
                for (int i = 0; i < n; ++i)
                    req[i] = k[i];

                long alr = 0;
                int lastDay = (int) (Math.min((long) 2e5, mid));

                for (int i = 0; i < m; ++i) {
                    if (p[i].day > mid)
                        continue;

                    if (lastDay > p[i].day)
                        lastDay = p[i].day;

                    while (lastDay > 0 && req[p[i].type] > 0) {
                        req[p[i].type]--;
                        lastDay--;
                        alr++;
                    }
                }

                long reqDays = 2 * totcnt - alr;
                if (reqDays <= mid) {
                    ans = mid;
                    end = mid - 1;
                } else {
                    start = mid + 1;
                }
            }

            out.print(ans);
        }

        class Pair {
            int day;
            int type;

            Pair(int a, int b) {
                day = a;
                type = b;
            }

        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();

            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }

                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();

            while (isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

import java.io.*;
import java.math.BigInteger;
import java.util.*;

public class test {
	public static void main(String[] args) throws IOException {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		PrintWriter out = new PrintWriter(outputStream);
		InputReader in = new InputReader(inputStream);

//		for(int i=4;i<=4;i++) {
//			InputStream uinputStream = new FileInputStream("leftout.in");
//			String f = i+".in";
//			InputStream uinputStream = new FileInputStream(f);
//			InputReader in = new InputReader(uinputStream);
//			PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("leftout.out")));
			Task t = new Task();
			t.solve(in, out);
			out.close();
//		}
	}

	static class Task {

		public void solve(InputReader in, PrintWriter out) throws IOException {
//			Dumper.print(Long.MAX_VALUE);
//			int n = in.nextInt();
//			long a[] = new long[n];
//			for(int i=0;i<n;i++) {
//				a[i] = in.nextLong();
//			}
//			pair c[] = new pair[n];
//			for(int i=0;i<n;i++) {
//				a[i] *= (i+1)*(n-i);
//				c[i] = new pair(-1*a[i],i);
//			}
//			Arrays.sort(c);
//
//			long b[] = new long[n];
//			long d[] = new long[n];
//			for(int i=0;i<n;i++) {
//				d[i] = in.nextLong();
//			}
//			ArrayUtils.sort(d);
//			for(int i=0;i<n;i++) {
//				b[c[i].idx] = d[i];
//			}
//			long f = 998244353;
//			long ret[] = new long[n];
//			for(int i=n-1;i>=0;i--) {
//				ret[i]=a[i];
//				ret[i]%=f;
//				ret[i]*=b[i];
//				ret[i]%=f;
//			}
//			long v = 0;
//			for(long tmp:ret) {
//				v+=tmp;
//				v%=f;
//			}
//			out.println(v);
			int n = in.nextInt();
			int m = in.nextInt();
			int s = 0;
			int sz = 200001;
			int need[] = new int[n+1];
			for(int i=1;i<=n;i++) {
				need[i] = in.nextInt();
				s+=need[i];
			}
			Set<Integer>[] g = new HashSet[sz];
			for(int i=1;i<sz;i++) g[i] = new HashSet<Integer>();
			for(int i=0;i<m;i++) {
				int d = in.nextInt();
				int t = in.nextInt();
				g[d].add(t);
			}

			int l = 1;
			int r = 2*sz;
			while(l<r-1) {
				int mid = l+(r-l)/2;
				if(is_ok(g,mid,need,s)) {
					r=mid;
				}else {
					l=mid;
				}
			}
			if(is_ok(g,l,need,s)) out.println(l);
			else out.println(r);
		}
		boolean is_ok(Set<Integer>[] g, int mid, int need[], int all) {
			int offer[] = new int[need.length];
			for(int i=1;i<=Math.min(mid, g.length-1);i++) {
				for(int j:g[i]) offer[j] = i;
			}
			ArrayList<offer> arr = new ArrayList<offer>();
			for(int i=1;i<offer.length;i++) {
				if(offer[i]!=0) arr.add(new offer(i,offer[i]));
			}
			Collections.sort(arr);
			int temp[] = need.clone();
			if(arr.size()==0) return mid>=2*all;
			int cur = 0; int p=0;
			for(int i=1;i<=mid;i++) {
				cur++;
				while(p<arr.size()&&i==arr.get(p).day) {
					int item = arr.get(p).item;
					int num = temp[item];
					if(cur>=num) {
						cur-=num;
						all-=num;
						temp[item]=0;
					}else if(cur<num) {
						temp[item]-=cur;
						all-=cur;
						cur=0;
					}
					p++;
				}
			}
			return cur>=2*all;
		}
		class offer implements Comparable<offer>{
			int item; int day;
			public offer(int a, int b) {
				item = a; day=b;
			}
			@Override
			public int compareTo(offer t) {
				return this.day-t.day;
			}
		}
		class pair implements Comparable<pair>{
			Long val; int idx;
			public pair(long a, int b) {
				val=a;idx=b;
			}
			@Override
			public int compareTo(pair t) {
				return this.val.compareTo(t.val);
			}
		}
		boolean is_prime(int a) {
			if(a==2||a==3) return true;
			for(int i=2;i<=Math.sqrt(a);i++) {
				if(a%i==0) return false;
			}
			return true;
		}

		class TreeNode {
			int val;
			TreeNode left;
			TreeNode right;
			TreeNode(int x) { val = x; }
		}

		public int GCD(int a, int b) {
		   if (b==0) return a;
		   return GCD(b,a%b);
		}
	}

    static class ArrayUtils {
        static final long seed = System.nanoTime();
        static final Random rand = new Random(seed);

        public static void sort(int[] a) {
            shuffle(a);
            Arrays.sort(a);
        }

        public static void shuffle(int[] a) {
            for (int i = 0; i < a.length; i++) {
                int j = rand.nextInt(i + 1);
                int t = a[i];
                a[i] = a[j];
                a[j] = t;
            }
        }

        public static void sort(long[] a) {
            shuffle(a);
            Arrays.sort(a);
        }

        public static void shuffle(long[] a) {
            for (int i = 0; i < a.length; i++) {
                int j = rand.nextInt(i + 1);
                long t = a[i];
                a[i] = a[j];
                a[j] = t;
            }
        }

    }
	static class BIT{
		int arr[];
		int n;
		public BIT(int a) {
			n=a;
			arr = new int[n];
		}
		int sum(int p) {
			int s=0;
			while(p>0) {
				s+=arr[p];
				p-=p&(-p);
			}
			return s;
		}
		void add(int p, int v) {
			while(p<n) {
				arr[p]+=v;
				p+=p&(-p);
			}
		}
	}
	static class DSU{
		int[] arr;
		int[] sz;
		public DSU(int n) {
			arr = new int[n];
			sz = new int[n];
			for(int i=0;i<n;i++) arr[i] = i;
			Arrays.fill(sz, 1);
		}
		public int find(int a) {
			if(arr[a]!=a) arr[a] = find(arr[a]);
			return arr[a];
		}
		public void union(int a, int b) {
			int x = find(a);
			int y = find(b);
			if(x==y) return;
			arr[x] = y;
			sz[y] += sz[x];
		}
		public int size(int x) {
			return sz[find(x)];
		}
	}
	static class MinHeap<Key> implements Iterable<Key> {
		private int maxN;
		private int n;
		private int[] pq;
		private int[] qp;
		private Key[] keys;
		private Comparator<Key> comparator;

		public MinHeap(int capacity){
			if (capacity < 0) throw new IllegalArgumentException();
			this.maxN = capacity;
			n=0;
			pq = new int[maxN+1];
			qp = new int[maxN+1];
			keys = (Key[]) new Object[capacity+1];
			Arrays.fill(qp, -1);
		}

		public MinHeap(int capacity, Comparator<Key> c){
			if (capacity < 0) throw new IllegalArgumentException();
			this.maxN = capacity;
			n=0;
			pq = new int[maxN+1];
			qp = new int[maxN+1];
			keys = (Key[]) new Object[capacity+1];
			Arrays.fill(qp, -1);
			comparator = c;
		}
		public boolean isEmpty()	{ return n==0; 	}
		public int size()			{ return n;		}
		public boolean contains(int i) {
	        if (i < 0 || i >= maxN) throw new IllegalArgumentException();
	        return qp[i] != -1;
		}
		public int peekIdx() {
	        if (n == 0) throw new NoSuchElementException("Priority queue underflow");
	        return pq[1];
		}
		public Key peek(){
			if(isEmpty()) throw new NoSuchElementException("Priority queue underflow");
			return keys[pq[1]];
		}
		public int poll(){
			if(isEmpty()) throw new NoSuchElementException("Priority queue underflow");
			int min = pq[1];
			exch(1,n--);
			down(1);
			assert min==pq[n+1];
			qp[min] = -1;
			keys[min] = null;
			pq[n+1] = -1;
			return min;
		}
	    public void update(int i, Key key) {
	        if (i < 0 || i >= maxN) throw new IllegalArgumentException();
	        if (!contains(i)) {
	        	this.add(i, key);
	        }else {
	        	keys[i] = key;
	        	up(qp[i]);
	        	down(qp[i]);
	        }
	    }
		private void add(int i, Key x){
	        if (i < 0 || i >= maxN) throw new IllegalArgumentException();
	        if (contains(i)) throw new IllegalArgumentException("index is already in the priority queue");
	        n++;
	        qp[i] = n;
	        pq[n] = i;
	        keys[i] = x;
	        up(n);
		}
		private void up(int k){
			while(k>1&&less(k,k/2)){
				exch(k,k/2);
				k/=2;
			}
		}
		private void down(int k){
			while(2*k<=n){
				int j=2*k;
				if(j<n&&less(j+1,j)) j++;
				if(less(k,j)) break;
				exch(k,j);
				k=j;
			}
		}

		public boolean less(int i, int j){
	        if (comparator == null) {
	            return ((Comparable<Key>) keys[pq[i]]).compareTo(keys[pq[j]]) < 0;
	        }
	        else {
	            return comparator.compare(keys[pq[i]], keys[pq[j]]) < 0;
	        }
		}

		public void exch(int i, int j){
	        int swap = pq[i];
	        pq[i] = pq[j];
	        pq[j] = swap;
	        qp[pq[i]] = i;
	        qp[pq[j]] = j;
		}

		@Override
		public Iterator<Key> iterator() {
			// TODO Auto-generated method stub
			return null;
		}
	}

    private static class InputReader
    {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int zcurChar;
        private int znumChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream)
        {
            this.stream = stream;
        }

        public int read()
        {
            if (znumChars == -1)
                throw new InputMismatchException();
            if (zcurChar >= znumChars)
            {
            	zcurChar = 0;
                try
                {
                    znumChars = stream.read(buf);
                } catch (IOException e)
                {
                    throw new InputMismatchException();
                }
                if (znumChars <= 0)
                    return -1;
            }
            return buf[zcurChar++];
        }

        public int nextInt()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public String nextString()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public double nextDouble()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.')
            {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.')
            {
                c = read();
                double m = 1;
                while (!isSpaceChar(c))
                {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public long nextLong()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c)
        {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next()
        {
            return nextString();
        }

        public interface SpaceCharFilter
        {
            public boolean isSpaceChar(int ch);
        }
        public int[] readIntArray(int n) {
            int[] ret = new int[n];
            for (int i = 0; i < n; i++) {
                ret[i] = nextInt();
            }
            return ret;
        }
    }

	static class Dumper {
		static void print_int_arr(int[] arr) {
			for (int i = 0; i < arr.length; i++) {
				System.out.print(arr[i] + " ");
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print_char_arr(char[] arr) {
			for (int i = 0; i < arr.length; i++) {
				System.out.print(arr[i] + " ");
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print_double_arr(double[] arr) {
			for (int i = 0; i < arr.length; i++) {
				System.out.print(arr[i] + " ");
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print_2d_arr(int[][] arr, int x, int y) {
			for (int i = 0; i < x; i++) {
				for (int j = 0; j < y; j++) {
					System.out.print(arr[i][j] + " ");
				}
				System.out.println();
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print_2d_arr(boolean[][] arr, int x, int y) {
			for (int i = 0; i < x; i++) {
				for (int j = 0; j < y; j++) {
					System.out.print(arr[i][j] + " ");
				}
				System.out.println();
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print(Object o) {
			System.out.println(o.toString());
		}

		static void getc() {
			System.out.println("here");
		}
	}
}

import sun.reflect.generics.tree.Tree;

import java.io.*;
import java.util.*;

public class Task {

    public static void main(String[] args) throws IOException {

        new Task().go();
    }

    PrintWriter out;
    Reader in;
    BufferedReader br;

    Task() throws IOException {

        try {

            //br = new BufferedReader( new FileReader("input.txt") );
            in = new Reader("input.txt");
            out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) );
        }
        catch (Exception e) {

            //br = new BufferedReader( new InputStreamReader( System.in ) );
            in = new Reader();
            out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
        }
    }

    void go() throws IOException {

        int t = 1;
        while (t > 0) {
            solve();
            //out.println();
            t--;
        }

        out.flush();
        out.close();
    }

    int inf = 2000000000;
    int mod = 1000000007;
    double eps = 0.000000001;

    int n;
    int m;
    ArrayList<Integer>[] g;
    void solve() throws IOException {

        int n = in.nextInt();
        int m = in.nextInt();
        int[] a = in.nextIntArray(n);

        g = new ArrayList[200010];
        for (int i = 0; i < g.length; i++)
            g[i] = new ArrayList<>();

        for (int i = 0; i < m; i++) {
            int x = in.nextInt();
            int y = in.nextInt();
            g[x].add(y - 1);
        }

        int l = 0;
        int r = 10000000;

        while (r > l) {
            int mid = (l + r) / 2;
            int[] b = new int[n];
            int sum = 0;

            int[] last = new int[n];

            for ( int i = 1; i <= mid; i++) {
                if (i < g.length)
                    for (int t : g[i]) {
                        last[t] = i;
                    }
            }

            for ( int i = 1; i <= mid; i++) {
                sum++;
                if (i < g.length)
                    for (int t : g[i]) {
                        if (last[t] == i) {
                            while (b[t] < a[t] && sum > 0) {
                                b[t]++;
                                sum--;
                            }
                        }
                    }
            }

            //System.err.println(mid + " " + sum);

            for (int i = 0; i < n; i++)
                sum -= 2 * (a[i] - b[i]);

            if (sum < 0)
                l = mid + 1;
            else
                r = mid;
        }

        out.print(r);
    }

    class Pair implements Comparable<Pair> {
        int a;
        int b;

        Pair(int a, int b) {
            this.a = a;
            this.b = b;
        }

        public int compareTo(Pair p) {
            if (a != p.a)
                return Integer.compare(a, p.a);
            else
                return Integer.compare(b, p.b);
        }
    }

    class Item {

        int a;
        int b;
        int c;

        Item(int a, int b, int c) {
            this.a = a;
            this.b = b;
            this.c = c;
        }

    }

    class Reader {

        BufferedReader  br;
        StringTokenizer tok;

        Reader(String file) throws IOException {
            br = new BufferedReader( new FileReader(file) );
        }

        Reader() throws IOException {
            br = new BufferedReader( new InputStreamReader(System.in) );
        }

        String next() throws IOException {

            while (tok == null || !tok.hasMoreElements())
                tok = new StringTokenizer(br.readLine());
            return tok.nextToken();
        }

        int nextInt() throws NumberFormatException, IOException {
            return Integer.valueOf(next());
        }

        long nextLong() throws NumberFormatException, IOException {
            return Long.valueOf(next());
        }

        double nextDouble() throws NumberFormatException, IOException {
            return Double.valueOf(next());
        }

        String nextLine() throws IOException {
            return br.readLine();
        }

        int[] nextIntArray(int n) throws IOException {
            int[] a = new int[n];
            for (int i = 0; i < n; i++)
                a[i] = nextInt();
            return a;
        }

        ArrayList<Integer>[] nextGraph(int n, int m) throws IOException {
            ArrayList<Integer>[] g = new ArrayList[n];
            for (int i = 0; i < n; i++)
                g[i] = new ArrayList<>();
            for (int i = 0; i < m; i++) {
                int x = nextInt() - 1;
                int y = nextInt() - 1;
                g[x].add(y);
                g[y].add(x);
            }

            return g;
        }

    }

}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;
import java.util.Map;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        Task1165F solver = new Task1165F();
        solver.solve(1, in, out);
        out.close();
    }

    static class Task1165F {
        ArrayList<Pair<Integer, Integer>> al = new ArrayList<>();

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            int arr[] = new int[n];
            int i, j, sum = 0;

            for (i = 0; i < n; i++) {
                arr[i] = in.nextInt();
                sum += arr[i];
            }

            for (i = 0; i < m; i++) {
                int d = in.nextInt();
                int t = in.nextInt() - 1;
                al.add(new Pair(d, t));
            }

            int low = sum;
            int high = 2 * sum;

            while (high - low > 1) {
                int mid = (high + low) / 2;
                int cur = check(arr, n, mid, sum);
                if (cur == 0)
                    high = mid;
                else
                    low = mid;
            }

            if (check(arr, n, low, sum) == 0)
                out.println(low);
            else
                out.println(high);
        }

        int check(int arra[], int n, int total_money, int suma) {
            int arr[] = Arrays.copyOf(arra, n);
            int sum = suma;
            int day[] = new int[n];

            int i, j;
            for (Pair t : al) {
                int first = (int) t.getFirst();
                int second = (int) t.getSecond();
                if (first > total_money)
                    continue;
                day[second] = Math.max(day[second], first);
            }

            TreeMap<Integer, Integer> tm = new TreeMap<>();
            for (i = 0; i < n; i++) {
                if (day[i] != 0) {
                    tm.put(day[i], tm.getOrDefault(day[i], 0) + arr[i]);
                }
            }
            //System.out.println(total_money +" " +tm);
            int cur_money = 0;
            for (i = 1; i <= total_money; i++) {
                cur_money++;
                int val = Math.min(tm.getOrDefault(i, 0), cur_money);
                cur_money -= val;
                sum -= val;
            }

            cur_money /= 2;
            sum -= cur_money;
            sum = Math.max(0, sum);
            return sum;
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void println(int i) {
            writer.println(i);
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class Pair<A, B> {
        A first;
        B second;

        public Pair(A first, B second) {
            super();
            this.first = first;
            this.second = second;
        }

        public int hashCode() {
            int hashFirst = first != null ? first.hashCode() : 0;
            int hashSecond = second != null ? second.hashCode() : 0;

            return (hashFirst + hashSecond) * hashSecond + hashFirst;
        }

        public boolean equals(Object other) {
            if (other instanceof Pair) {
                Pair otherPair = (Pair) other;
                return
                        ((this.first == otherPair.first ||
                                (this.first != null && otherPair.first != null &&
                                        this.first.equals(otherPair.first))) &&
                                (this.second == otherPair.second ||
                                        (this.second != null && otherPair.second != null &&
                                                this.second.equals(otherPair.second))));
            }

            return false;
        }

        public String toString() {
            return "(" + first + ", " + second + ")";
        }

        public A getFirst() {
            return first;
        }

        public B getSecond() {
            return second;
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.stream.IntStream;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in Actual solution is at the top
 *
 * @author NMouad21
 */
public class Main {

  public static void main(String[] args) {
    InputStream inputStream = System.in;
    OutputStream outputStream = System.out;
    InputReader in = new InputReader(inputStream);
    PrintWriter out = new PrintWriter(outputStream);
    F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
    solver.solve(1, in, out);
    out.close();
  }

  static class F2MicrotransactionsHardVersion {

    public void solve(int testNumber, InputReader in, PrintWriter out) {
      int n = in.nextInt();
      int m = in.nextInt();
      int[] k = in.nextIntArrayOneBased(n);
      final int sum = IntStream.of(k).sum();
      final int maxDay = (int) 2e5;

      ArrayList<Integer>[] s = (ArrayList<Integer>[]) new ArrayList[maxDay + 1];
      for (int i = 0; i < s.length; i++) {
        s[i] = new ArrayList<>();
      }
      for (int i = 0; i < m; i++) {
        int d = in.nextInt();
        int t = in.nextInt();
        s[d].add(t);
      }

      int lo = 0, hi = (int) 5e5, ans = hi;
      while (lo <= hi) {
        int mid = (lo + hi) / 2;
        if (sum * 2 - saved(s, Arrays.copyOf(k, k.length), Math.min(mid + 1, s.length), n) <= mid) {
          hi = mid - 1;
          ans = mid;
        } else {
          lo = mid + 1;
        }
      }

      out.println(ans);
    }

    private int saved(ArrayList<Integer>[] s, int[] k, int length, int n) {
      int[] lastSale = new int[n + 1];
      for (int i = 1; i < length; i++) {
        for (int type : s[i]) {
          lastSale[type] = i;
        }
      }

      int saved = 0, has = 0;
      for (int i = 1; i < length; i++) {
        ++has;
        for (int type : s[i]) {
          if (i == lastSale[type]) {
            int win = Math.min(has, k[type]);
            saved += win;
            k[type] -= win;
            has -= win;
          }
        }
      }

      return saved;
    }

  }

  static class InputReader {

    private InputStream stream;
    private static final int DEFAULT_BUFFER_SIZE = 1 << 16;
    private static final int EOF = -1;
    private byte[] buf = new byte[DEFAULT_BUFFER_SIZE];
    private int curChar;
    private int numChars;

    public InputReader(InputStream stream) {
      this.stream = stream;
    }

    public int read() {
      if (this.numChars == EOF) {
        throw new UnknownError();
      } else {
        if (this.curChar >= this.numChars) {
          this.curChar = 0;

          try {
            this.numChars = this.stream.read(this.buf);
          } catch (IOException ex) {
            throw new InputMismatchException();
          }

          if (this.numChars <= 0) {
            return EOF;
          }
        }

        return this.buf[this.curChar++];
      }
    }

    public int nextInt() {
      int c;
      for (c = this.read(); isSpaceChar(c); c = this.read()) {
      }

      byte sgn = 1;
      if (c == 45) {
        sgn = -1;
        c = this.read();
      }

      int res = 0;

      while (c >= 48 && c <= 57) {
        res *= 10;
        res += c - 48;
        c = this.read();
        if (isSpaceChar(c)) {
          return res * sgn;
        }
      }

      throw new InputMismatchException();
    }

    public static boolean isSpaceChar(int c) {
      return c == 32 || c == 10 || c == 13 || c == 9 || c == EOF;
    }

    public int[] nextIntArrayOneBased(int n) {
      int[] ret = new int[n + 1];
      for (int i = 1; i <= n; i++) {
        ret[i] = nextInt();
      }
      return ret;
    }

  }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author KharYusuf
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastReader in = new FastReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
        solver.solve(1, in, out);
        out.close();
    }

    static class F2MicrotransactionsHardVersion {
        public void solve(int testNumber, FastReader s, PrintWriter w) {
            int n = s.nextInt(), m = s.nextInt(), MX = (int) 2e5;
            int[] re = new int[n], last = new int[n];
            long sum = 0;
            ArrayList<Integer>[] offers = new ArrayList[MX + 1];
            for (int i = 0; i <= MX; i++) offers[i] = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                re[i] = s.nextInt();
                sum += re[i];
            }
            while (m-- > 0) offers[s.nextInt()].add(s.nextInt() - 1);
            long l = 1, r = sum << 1;
            while (l <= r) {
                int[] req = re.clone();
                long mid = l + r >> 1, cur = sum;
                int has = 0;
                for (int i = 1; i <= Math.min(MX, mid); i++) for (int j : offers[i]) last[j] = i;
                for (int i = 1; i <= Math.min(MX, mid); i++) {
                    has++;
                    for (int j : offers[i])
                        if (req[j] > 0 && last[j] == i) {
                            int take = Math.min(has, req[j]);
                            req[j] -= take;
                            has -= take;
                            cur -= take;
                        }
                }
                has += Math.max(0, mid - MX);
                if (cur * 2 <= has) r = mid - 1;
                else l = mid + 1;
            }
            w.println(++r);
        }

    }

    static class FastReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private FastReader.SpaceCharFilter filter;

        public FastReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {

            if (numChars == -1)
                throw new InputMismatchException();

            if (curChar >= numChars) {

                curChar = 0;

                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }

                if (numChars <= 0)
                    return -1;
            }

            return buf[curChar++];
        }

        public int nextInt() {

            int c = read();

            while (isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();

                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public boolean isSpaceChar(int c) {

            if (filter != null)
                return filter.isSpaceChar(c);

            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

import java.io.*;
import java.util.*;

public class ProblemF_1 {

    public static InputStream inputStream = System.in;

    public static OutputStream outputStream = System.out;

    public static void main(String[] args) {
        MyScanner scanner = new MyScanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);

        int n = scanner.nextInt();
        int m = scanner.nextInt();
        List<Integer> amounts = new ArrayList<>();
        List<Pair<Integer, Integer>> salePairs = new ArrayList<>();
        int s = 0;
        for (int i = 0; i < n; i++) {
            int x = scanner.nextInt();
            s = s + x;
            amounts.add(x);
        }

        for (int i = 0; i < m; i++) {
            salePairs.add(new Pair<>(scanner.nextInt(), scanner.nextInt()));
        }

        out.println(solve(amounts, salePairs, s, 1, 2 * s));

        out.flush();
    }

    private static int solve(List<Integer> amounts, List<Pair<Integer, Integer>> salePairs, int sum, int l, int r) {
        if (l == r) {
            return l;
        }
        if (l + 1 == r) {
            if (canSolve(amounts, salePairs, sum, l)) {
                return l;
            } else {
                return r;
            }
        }
        int mid = (l + r) / 2;
        if (canSolve(amounts, salePairs, sum, mid)) {
            return solve(amounts, salePairs, sum, l, mid);
        } else {
            return solve(amounts, salePairs, sum, mid + 1, r);
        }
    }

    private static boolean canSolve(List<Integer> amounts, List<Pair<Integer, Integer>> salePairs, int sum, int lastDay) {
        Map<Integer, Integer> map = new HashMap<>();
        for (Pair<Integer, Integer> pair : salePairs) {
            if (pair.first <= lastDay) {
                if (map.containsKey(pair.second)) {
                    if (map.get(pair.second) < pair.first) {
                        map.put(pair.second, pair.first);
                    }
                } else {
                    map.put(pair.second, pair.first);
                }
            }
        }

        Map<Integer, List<Integer>> sales = new HashMap<>();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (!sales.containsKey(entry.getValue())) {
                sales.put(entry.getValue(), new ArrayList<>());
            }
            sales.get(entry.getValue()).add(entry.getKey());
        }

        int x = 0;
        for (int i = 1; i <= lastDay; i++) {
            x++;
            if (sales.containsKey(i)) {
                for (int t : sales.get(i)) {
                    if (x > amounts.get(t - 1)) {
                        sum = sum - amounts.get(t - 1);
                        x = x - amounts.get(t - 1);
                    } else {
                        sum = sum - x;
                        x = 0;
                    }
                }
            }
            if (sum * 2 <= x) {
                break;
            }
        }
        return sum * 2 <= x;
    }

    private static class MyScanner {
        private BufferedReader bufferedReader;
        private StringTokenizer stringTokenizer;

        private MyScanner(InputStream inputStream) {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        }

        private String next() {
            while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) {
                try {
                    stringTokenizer = new StringTokenizer(bufferedReader.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return stringTokenizer.nextToken();
        }

        private int nextInt() {
            return Integer.parseInt(next());
        }

        private long nextLong() {
            return Long.parseLong(next());
        }

        private double nextDouble() {
            return Double.parseDouble(next());
        }

        private String nextLine() {
            String str = "";
            try {
                str = bufferedReader.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }

    private static class Pair<F, S> {

        private F first;

        private S second;

        public Pair() {
        }

        public Pair(F first, S second) {
            this.first = first;
            this.second = second;
        }
    }
}

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;

public class Main {
	private static final long MOD = 1000000007;
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve() {
		int n = ni();
		int k = ni();
		int[] a = na(n);

		int dis[][] = na(k, 2);
		Arrays.sort(dis, new Comparator<int[]>() {
			public int compare(int[] o1, int[] o2) {
				return o2[0] - o1[0];
			}
		});

//		tr(dis);
		long sum = Arrays.stream(a).asLongStream().sum() * 2;

		long l = 0;
		long r = sum * 2;
		while (l < r) {
			long m = (l + r) / 2;
			long lastDay = m;
			long deals = 0;
			int[] req = Arrays.copyOf(a, n);
			for (int i = 0; i < k; i++) {
				if (dis[i][0] > m)
					continue;
				if (dis[i][0] < lastDay)
					lastDay = dis[i][0];
				if (lastDay > 0 && req[dis[i][1] - 1] > 0) {
					long canBuy = Math.min(lastDay, req[dis[i][1] - 1]);
					req[dis[i][1] - 1] -= canBuy;
					lastDay -= canBuy;
					deals += canBuy;
//					tr("-", i, deals, canBuy, lastDay);
				}
			}
//			tr(sum, deals, l, r, m);
			if (sum - deals > m)
				l = m + 1;
			else
				r = m;
		}

		out.println(r);
	}

	StringBuffer sb = new StringBuffer();

	void run() throws Exception {
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);
		Thread t = new Thread(null, null, "~", Runtime.getRuntime().maxMemory()) {
			@Override
			public void run() {
				long s = System.currentTimeMillis();
				solve();
				out.flush();
				if (!INPUT.isEmpty())
					tr(System.currentTimeMillis() - s + "ms");
			}
		};
		t.start();
		t.join();

		// long s = System.currentTimeMillis();
		// solve();
		// out.flush();
		// if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
	}

	public static void main(String[] args) throws Exception {
		new Main().run();
	}

	private byte[] inbuf = new byte[1024];
	public int lenbuf = 0, ptrbuf = 0;

	private int readByte() {
		if (lenbuf == -1)
			throw new InputMismatchException();
		if (ptrbuf >= lenbuf) {
			ptrbuf = 0;
			try {
				lenbuf = is.read(inbuf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (lenbuf <= 0)
				return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c) {
		return !(c >= 33 && c <= 126);
	}

	private int skip() {
		int b;
		while ((b = readByte()) != -1 && isSpaceChar(b))
			;
		return b;
	}

	private double nd() {
		return Double.parseDouble(ns());
	}

	private char nc() {
		return (char) skip();
	}

	private String ns() {
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n) {
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while (p < n && !(isSpaceChar(b))) {
			buf[p++] = (char) b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m) {
		char[][] map = new char[n][];
		for (int i = 0; i < n; i++)
			map[i] = ns(m);
		return map;
	}

	private int[] na(int n) {
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}

	private int[][] na(int n, int m) {
		int[][] a = new int[n][];
		for (int i = 0; i < n; i++)
			a[i] = na(m);
		return a;
	}

	private int ni() {
		int num = 0, b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl() {
		long num = 0;
		int b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private int max(int[] a) {
		int ret = Integer.MIN_VALUE;
		for (int i : a)
			ret = Math.max(ret, i);
		return ret;
	}

	private static void tr(Object... o) {
		System.out.println(Arrays.deepToString(o));
	}
}

import java.io.*;
import java.util.*;
import java.math.*;

public class F{
  final int mod = 1000000007;
  final int maxn = (int)4e5 + 3;
  final double eps = 1e-9;

  int n, m;
  int[] k = new int[maxn];
  List<Integer>[] dayOffer = new ArrayList[maxn + 1];
  {
    for(int i = 0; i < dayOffer.length; ++i){
      dayOffer[i] = new ArrayList();
    }
  }

  boolean can(int day){
    int burles = 0;
    int[] offer = new int[maxn];
    for(int d = 1; d <= day; ++d){
      for(int i : dayOffer[d]){
        offer[i] = Math.max(offer[i], d);
      }
    }
    List<Integer>[] sale = new ArrayList[maxn];
    for(int i = 0; i < sale.length; ++i){
      sale[i] = new ArrayList<Integer>();
    }
    for(int i = 0; i < n; ++i){
      sale[offer[i]].add(i);
    }
    int[] buy = new int[maxn];
    for(int d = 1; d <= day; ++d){
      ++burles;
      for(int i : sale[d]){
        buy[i] = Math.min(k[i], burles);
        burles -= buy[i];
      }
    }
    for(int i = 0; i < n; ++i){
      burles -= 2 * (k[i] - buy[i]);
    }
    return burles >= 0;
  }

  void main(){
    // freopen("in");
    n = nextInt();
    m = nextInt();
    int sum = 0;
    for(int i = 0; i < n; ++i){
      k[i] = nextInt();
      sum += k[i];
    }
    for(int i = 0; i < m; ++i){
      int d = nextInt();
      int t = nextInt() - 1;
      dayOffer[d].add(t);
    }
    int i = 1, j = 2 * sum;
    while(i < j){
      int day = (i + j) / 2;
      if(!can(day)){
        i = day + 1;
      }
      else{
        j = day;
      }
    }
    printf("%d\n", i);
  }

  final double pi = Math.acos(-1.0);
  final long infl = 0x3f3f3f3f3f3f3f3fl;
  final int inf = 0x3f3f3f3f;
  final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

  boolean zero(double x){ return x < eps; }

  PrintWriter out = new PrintWriter(System.out);
  BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 1 << 15);
  StringTokenizer tokens = new StringTokenizer("");

  F(){
    Locale.setDefault(Locale.US);       // imprime double com ponto
    main();
    out.close();
  }

  void freopen(String s){ try{ reader = new BufferedReader(new InputStreamReader(new FileInputStream(s)), 1 << 15); } catch(FileNotFoundException e){ throw new RuntimeException(e); } }

  int nextInt(){ return Integer.parseInt(next()); }
  long nextLong(){ return Long.parseLong(next()); }
  double nextDouble(){ return Double.parseDouble(next()); }
  String next(){ readTokens(); return tokens.nextToken(); }
  String nextLine(){ readTokens(); return tokens.nextToken("\n"); }

  void readTokens(){
    while(!tokens.hasMoreTokens())      // lê os dados, ignorando linhas vazias
      try{ tokens = new StringTokenizer(reader.readLine()); } catch(IOException e){ throw new RuntimeException(e); }
  }

  void printf(String s, Object... o){ out.printf(s, o); }
  void debug(String s, Object... o){ if(!ONLINE_JUDGE) System.err.printf((char)27 + "[91m" + s + (char)27 + "[0m", o); }

  public static void main(String[] args){ new F(); }
}

import java.io.*;
import java.util.*;

public class b
{
    public static void print(String str,long val){
        System.out.println(str+"  "+val);
    }

    public long gcd(long a, long b) {
        if (b==0L) return a;
        return gcd(b,a%b);
    }

    public static void debug(long[][] arr){
        int len = arr.length;
        for(int i=0;i<len;i++){
            System.out.println(Arrays.toString(arr[i]));
        }
    }
    public static void debug(int[][] arr){
        int len = arr.length;
        for(int i=0;i<len;i++){
            System.out.println(Arrays.toString(arr[i]));
        }
    }
    public static void debug(String[] arr){
        int len = arr.length;
        for(int i=0;i<len;i++){
            System.out.println(arr[i]);
        }
    }

    public static void print(int[] arr){
        int len = arr.length;
        for(int i=0;i<len;i++){
            System.out.print(arr[i]+" ");
        }
        System.out.print('\n');
    }

    public static void print(Object[] arr){
        int len = arr.length;
        for(int i=0;i<len;i++){
            System.out.print(arr[i]+" ");
        }
        System.out.print('\n');
    }
    public static void print(String[] arr){
        int len = arr.length;
        for(int i=0;i<len;i++){
            System.out.print(arr[i]+" ");
        }
        System.out.print('\n');
    }
    public static void print(long[] arr){
        int len = arr.length;
        for(int i=0;i<len;i++){
            System.out.print(arr[i]+" ");
        }
        System.out.print('\n');
    }

    static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                    InputStreamReader(System.in));
        }
        public FastReader(String path) throws FileNotFoundException {
            br = new BufferedReader(new FileReader(path));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }

    static void sort(long[] arr){
        Long[] temp = new Long[arr.length];
        for(int i=0;i<arr.length;i++){
            temp[i] = arr[i];
        }
        Arrays.sort(temp);
        for(int i=0;i<arr.length;i++){
            arr[i] = temp[i];
        }
    }

    static int[] copies;
    static pair[] days;
    static int n;
    static int m;
    public static void main(String[] args)
    {
        FastReader s=new FastReader();
        n = s.nextInt();
        m = s.nextInt();
        copies = new int[n];
        for(int i=0;i<n;i++){
            copies[i] = s.nextInt();
        }
        days = new pair[m];
        for (int i=0;i<m;i++){
            int day = s.nextInt();
            int type = s.nextInt()-1;
            days[i] = new pair(day,type);
        }
        Arrays.sort(days);
        int start =1;
        int end = 4*(100005);
        while (end-start>1){
            int mid = (end+start)/2;
            if(check(mid)){
                end = mid;
            }
            else start = mid+1;
        }
        if(check(start)) System.out.println(start);
        else System.out.println(end);
//        check(5);

    }

    static boolean check(int k){
        boolean[] visited = new boolean[n];
        ArrayList<Integer>[] last_day = new ArrayList[k+1];
        for(int i=0;i<=k;i++){
            last_day[i] = new ArrayList<>();
        }
        for(int i=m-1;i>=0;i--){
            if(days[i].day>k){
                continue;
            }
            else {
                if(!visited[days[i].type]){
                    visited[days[i].type] = true;
                    last_day[days[i].day].add(days[i].type);
                }
            }
        }
//        print(last_day);
        int cost =0;
        int[] required = copies.clone();
        for(int i=1;i<=k;i++){
            if(last_day[i].size()==0){
                cost++;
            }
            else {
                cost++;
                for(int child:last_day[i]){
                    if(required[child]>0){
                        if(cost>=required[child]){
                            cost-=required[child];
                            required[child] =0;
                        }
                        else {
                            int temp = Math.min(cost,required[child]);
                            cost-=temp;
                            required[child]-=temp;
                        }
                    }
                }
            }

        }
        int total =0;
        for(int i=0;i<n;i++){
            total+=required[i];
        }
        if(cost>=2*total){
            return true;
        }
        return false;
    }

    static class pair implements  Comparable<pair>{
        int day;
        int type;
        pair(int day,int type) {
            this.day = day;
            this.type = type;
        }
        public int compareTo(pair p){
            return Integer.compare(this.day,p.day);
        }
    }

//    OutputStream out = new BufferedOutputStream( System.out );
//        for(int i=1;i<n;i++){
//              out.write((arr[i]+" ").getBytes());
//         }
//        out.flush();
//  long start_time = System.currentTimeMillis();
//  long end_time = System.currentTimeMillis();
//  System.out.println((end_time - start_time) + "ms");

}

import java.io.*;
import java.text.*;
import java.util.*;
import java.math.*;
public class template {
	public static void main(String[] args) throws Exception {
		new template().run();
	}
	public void run() throws Exception {
		FastScanner f = new FastScanner();
		PrintWriter out = new PrintWriter(System.out);
		int n = f.nextInt(), m = f.nextInt();
		int[] nec = new int[n];
		int tot = 0;
		for(int i = 0; i < n; i++) tot += nec[i] = f.nextInt();
		LinkedList<Integer>[] ll = new LinkedList[200000];
		for(int i = 0; i < ll.length; i++) ll[i] = new LinkedList<>();
		for(int i = 0; i < m; i++) {
			int a = f.nextInt(), b = f.nextInt();
			ll[a-1].add(b-1);
		}
		int lo = 1, hi = tot*2;
		while(lo < hi) {
			int mid = (lo+hi)/2;
			int total = tot;
			int y = mid;
			int z = mid;
			int[] cnt = new int[n];
			for(int i = mid-1; i >= 0; i--) {
				y = Math.min(y, i+1);
				if(i < ll.length) for(int a : ll[i])
					while(y > 0 && cnt[a] < nec[a]) {
						cnt[a]++;
						y--;
						z--;
						total--;
					}
			}
			if(total * 2 <= z) hi = mid;
			else lo = mid+1;
		}
		out.println(lo);
 		out.flush();
	}
	public static final long MOD = 998244353;
    static class FastScanner {
        public BufferedReader reader;
        public StringTokenizer tokenizer;
        public FastScanner() {
            reader = new BufferedReader(new InputStreamReader(System.in), 32768);
            tokenizer = null;
        }
        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }
        public int nextInt() {
            return Integer.parseInt(next());
        }
        public long nextLong() {
        	return Long.parseLong(next());
        }
        public double nextDouble() {
        	return Double.parseDouble(next());
        }
        public String nextLine() {
        	try {
        		return reader.readLine();
        	} catch(IOException e) {
        		throw new RuntimeException(e);
        	}
        }
    }
}

import java.io.*;
import java.nio.CharBuffer;
import java.util.HashSet;
import java.util.NoSuchElementException;

public class P1165F2 {

    private static final int MAX = 200000;

    public static void main(String[] args) {
        SimpleScanner scanner = new SimpleScanner(System.in);
        PrintWriter writer = new PrintWriter(System.out);

        int n = scanner.nextInt();
        int m = scanner.nextInt();
        int[] target = new int[n];
        int sum = 0;
        for (int i = 0; i < n; ++i) {
            target[i] = scanner.nextInt();
            sum += target[i];
        }
        HashSet<Integer>[] sales = new HashSet[MAX + 1];
        for (int i = 0; i < m; ++i) {
            int d = scanner.nextInt();
            int t = scanner.nextInt() - 1;
            if (sales[d] == null)
                sales[d] = new HashSet<>();
            sales[d].add(t);
        }
        int l = sum, r = 2 * sum;
        while (l < r) {
            int mid = (l + r) >> 1;
            if (!test(target.clone(), sales, sum, mid))
                l = mid + 1;
            else
                r = mid;
        }
        writer.println(l);

        writer.close();
    }

    private static boolean test(int[] target, HashSet<Integer>[] sales, int sum, int k) {
        int mostSale = 0;
        for (int day = Math.min(k, MAX), fund = Math.min(k, MAX); fund > 0; --day, fund = Math.min(fund, day)) {
            if (sales[day] != null) {
                for (int sale : sales[day]) {
                    if (target[sale] > 0) {
                        int num = Math.min(fund, target[sale]);
                        target[sale] -= num;
                        fund -= num;
                        mostSale += num;
                    }
                }
            }
        }
        return 2 * sum - mostSale <= k;
    }

    private static class SimpleScanner {

        private static final int BUFFER_SIZE = 10240;

        private Readable in;
        private CharBuffer buffer;
        private boolean eof;

        SimpleScanner(InputStream in) {
            this.in = new BufferedReader(new InputStreamReader(in));
            buffer = CharBuffer.allocate(BUFFER_SIZE);
            buffer.limit(0);
            eof = false;
        }

        private char read() {
            if (!buffer.hasRemaining()) {
                buffer.clear();
                int n;
                try {
                    n = in.read(buffer);
                } catch (IOException e) {
                    n = -1;
                }
                if (n <= 0) {
                    eof = true;
                    return '\0';
                }
                buffer.flip();
            }
            return buffer.get();
        }

        void checkEof() {
            if (eof)
                throw new NoSuchElementException();
        }

        char nextChar() {
            checkEof();
            char b = read();
            checkEof();
            return b;
        }

        String next() {
            char b;
            do {
                b = read();
                checkEof();
            } while (Character.isWhitespace(b));
            StringBuilder sb = new StringBuilder();
            do {
                sb.append(b);
                b = read();
            } while (!eof && !Character.isWhitespace(b));
            return sb.toString();
        }

        int nextInt() {
            return Integer.valueOf(next());
        }

        long nextLong() {
            return Long.valueOf(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }
    }
}

import java.util.*;

 public class Solution
{
       static int k[];
       static int offer[][];

       static boolean check(int x)
       {

              int o[] = new int[1001];
              int money = 0;
              int total = 0;
              for(int i = 0 ; i < offer.length ; i++)
              {

                     if(offer[i][0] > o[offer[i][1]] && offer[i][0] <= x)
                     o[offer[i][1]] = offer[i][0];
              }

              for(int i = 0 ; i < Math.min(k.length,x) ; i++)
              {
                     money++;
                     for(int j = 1 ; j <= k.length ; j++)
                     {

                           if(o[j] != 0 && o[j] == i+1)
                           {
                                  total += Math.min(money , k[j-1]);
                            money = Math.max(0 , money-k[j-1]);

                           }

                     }

              }
              int T = 0;
              for(int i = 0 ; i < k.length ; i++)
              {
                     T += k[i];
              }
              T -= total;

             if(x > k.length)
             money = money+x-k.length;

              if(money >= 2*T)
              return true;

              return false;
       }
       public static void main(String []args)
       {
              Scanner sc = new Scanner(System.in);
              int n = sc.nextInt();
              int m = sc.nextInt();
              k = new int[n];
              for(int i = 0 ; i < n ; i++)
              {
                     k[i] = sc.nextInt();
              }
              offer = new int[m][2];
              for(int i = 0 ; i < m ; i++)
              {
                     offer[i][0] = sc.nextInt();
                     offer[i][1] = sc.nextInt();
              }
              int l = 1 , r = 1000000;
             while(l <  r)
              {
                     int mid = (l+r)/2;
                     boolean c = check(mid);
                     if(c)
                     r = mid;

                     else
                     l = mid+1;

              }

             System.out.println(l);
       }
}

import java.util.*;

public class Solution
{
       static int k[];
       static int offer[][];

       static boolean check(int x)
       {
              if(x < k.length)
              return false;

              int o[] = new int[1001];
              int money = 0;
              int total = 0;
              for(int i = 0 ; i < offer.length ; i++)
              {
                     o[offer[i][1]] = Math.max(offer[i][0],o[offer[i][1]]);
              }

              for(int i = 0 ; i < k.length ; i++)
              {
                     money++;
                     for(int j = 1 ; j <= k.length ; j++)
                     {

                           if(o[j] != 0 && o[j] == i+1)
                           {
                                  total += Math.min(money , k[j-1]);
                            money = Math.max(0 , money-k[j-1]);

                           }

                     }

              }
              int T = 0;
              for(int i = 0 ; i < k.length ; i++)
              {
                     T += k[i];
              }
              T -= total;

              if(money + x - k.length >= 2*T)
              return true;

              return false;
       }
       public static void main(String []args)
       {
              Scanner sc = new Scanner(System.in);
              int n = sc.nextInt();
              int m = sc.nextInt();
              k = new int[n];
              for(int i = 0 ; i < n ; i++)
              {
                     k[i] = sc.nextInt();
              }
              offer = new int[m][2];
              for(int i = 0 ; i < m ; i++)
              {
                     offer[i][0] = sc.nextInt();
                     offer[i][1] = sc.nextInt();
              }
              int l = 1 , r = 1000000;
             while(l <  r)
              {
                     int mid = (l+r)/2;
                     boolean c = check(mid);
                     if(c)
                     r = mid;

                     else
                     l = mid+1;

              }

             System.out.println(l);
       }
}

/*
    Author: Anthony Ngene
    Created: 04/10/2020 - 12:12
*/

import java.io.*;
import java.util.*;

public class F {
// checks: 1. edge cases   2. overflow   3. possible errors (e.g 1/0, arr[out])   4. time/space complexity
    void solver() throws IOException {
        int n = in.intNext(), m = in.intNext();
        int[] arr = in.nextIntArray(n);
        int required = sum(arr);
        HashMap<Integer, Tuple> lastSaleday = new HashMap<>();
        int[][] saleArr = new int[m][2];
        for (int i = 0; i < m; i++) {
            int day = in.intNext(), typ = in.intNext();
            if (arr[typ - 1] <= 0) continue;
            saleArr[i][0] = day;
            saleArr[i][1] = typ;
            if (!lastSaleday.containsKey(typ)) lastSaleday.put(typ, new Tuple(day, 0, typ));
        }
//        out.println(lastSaleday);
        HashMap<Integer, TreeSet<Tuple>> days = new HashMap<>();
        for (int i = 0; i < m; i++) {
            int day = saleArr[i][0], typ = saleArr[i][1];
            if (typ == 0 || arr[typ - 1] <= 0) continue;
            if (!days.containsKey(day)) days.put(day, new TreeSet<>());
            days.get(day).add(lastSaleday.get(typ));
        }
//        out.println(days);
        int day = 0;
        int coin = 0;
        while (required * 2 > coin) {
            day++;
            coin++;
            while (coin > 0 && days.containsKey(day) && !days.get(day).isEmpty()) {
                Tuple typ = days.get(day).pollFirst();
                int rem = arr[typ.c - 1];
                int mn = min(rem, coin);
                arr[typ.c - 1] -= mn;
                required -= mn;
                coin -= mn;
            }
        }
        out.println(day);
    }

// Generated Code Below:
private static final FastWriter out = new FastWriter();
private static FastScanner in;
static ArrayList<Integer>[] adj;
private static long e97 = (long)1e9 + 7;
public static void main(String[] args) throws IOException {
    in = new FastScanner();
    new F().solver();
    out.close();
}

static class FastWriter {
    private static final int IO_BUFFERS = 128 * 1024;
    private final StringBuilder out;
    public FastWriter() { out = new StringBuilder(IO_BUFFERS); }
    public FastWriter p(Object object) { out.append(object); return this; }
    public FastWriter p(String format, Object... args) { out.append(String.format(format, args)); return this; }
    public FastWriter pp(Object... args) { for (Object ob : args) { out.append(ob).append(" ");  } out.append("\n"); return this; }
    public FastWriter pp(int[] args) { for (int ob : args) { out.append(ob).append(" ");  } out.append("\n"); return this; }
    public FastWriter pp(long[] args) { for (long ob : args) { out.append(ob).append(" ");  } out.append("\n"); return this; }
    public FastWriter pp(char[] args) { for (char ob : args) { out.append(ob).append(" ");  } out.append("\n"); return this; }
    public void println(long[] arr) { for(long e: arr) out.append(e).append(" "); out.append("\n"); }
    public void println(int[] arr) { for(int e: arr) out.append(e).append(" "); out.append("\n"); }
    public void println(char[] arr) { for(char e: arr) out.append(e).append(" "); out.append("\n"); }
    public void println(double[] arr) { for(double e: arr) out.append(e).append(" "); out.append("\n"); }
    public void println(boolean[] arr) { for(boolean e: arr) out.append(e).append(" "); out.append("\n"); }
    public <T>void println(T[] arr) { for(T e: arr) out.append(e).append(" "); out.append("\n"); }
    public void println(long[][] arr) {  for (long[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
    public void println(int[][] arr) {  for (int[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
    public void println(char[][] arr) {  for (char[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
    public void println(double[][] arr) {  for (double[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
    public <T>void println(T[][] arr) {  for (T[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
    public FastWriter println(Object object) { out.append(object).append("\n"); return this; }
    public void toFile(String fileName) throws IOException {
        BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
        writer.write(out.toString());
        writer.close();
    }
    public void close() throws IOException { System.out.print(out); }
}
static class FastScanner {
    private InputStream sin = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;
    public FastScanner(){}
    public FastScanner(String filename) throws FileNotFoundException {
        File file = new File(filename);
        sin = new FileInputStream(file);
    }
    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        }else{
            ptr = 0;
            try {
                buflen = sin.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }
    private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
    private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
    public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
    public String next() {
        if (!hasNext()) throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while(isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }
    public long longNext() {
        if (!hasNext()) throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while(true){
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            }else if(b == -1 || !isPrintableChar(b) || b == ':'){
                return minus ? -n : n;
            }else{
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }
    public int intNext() {
        long nl = longNext();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
        return (int) nl;
    }
    public double doubleNext() { return Double.parseDouble(next());}
    public long[] nextLongArray(final int n){
        final long[] a = new long[n];
        for (int i = 0; i < n; i++)
            a[i] = longNext();
        return a;
    }
    public int[] nextIntArray(final int n){
        final int[] a = new int[n];
        for (int i = 0; i < n; i++)
            a[i] = intNext();
        return a;
    }
    public double[] nextDoubleArray(final int n){
        final double[] a = new double[n];
        for (int i = 0; i < n; i++)
            a[i] = doubleNext();
        return a;
    }
    public ArrayList<Integer>[] getAdj(int n) {
        ArrayList<Integer>[] adj = new ArrayList[n + 1];
        for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>();
        return adj;
    }
    public ArrayList<Integer>[] adjacencyList(int nodes, int edges) throws IOException {
        return adjacencyList(nodes, edges, false);
    }
    public ArrayList<Integer>[] adjacencyList(int nodes, int edges, boolean isDirected) throws IOException {
        adj = getAdj(nodes);
        for (int i = 0; i < edges; i++) {
            int a = intNext(), b = intNext();
            adj[a].add(b);
            if (!isDirected) adj[b].add(a);
        }
        return adj;
    }
}
static class u {
    public static int upperBound(long[] array, long obj) {
        int l = 0, r = array.length - 1;
        while (r - l >= 0) {
            int c = (l + r) / 2;
            if (obj < array[c]) {
                r = c - 1;
            } else {
                l = c + 1;
            }
        }
        return l;
    }
    public static int upperBound(ArrayList<Long> array, long obj) {
        int l = 0, r = array.size() - 1;
        while (r - l >= 0) {
            int c = (l + r) / 2;
            if (obj < array.get(c)) {
                r = c - 1;
            } else {
                l = c + 1;
            }
        }
        return l;
    }
    public static int lowerBound(long[] array, long obj) {
        int l = 0, r = array.length - 1;
        while (r - l >= 0) {
            int c = (l + r) / 2;
            if (obj <= array[c]) {
                r = c - 1;
            } else {
                l = c + 1;
            }
        }
        return l;
    }
    public static int lowerBound(ArrayList<Long> array, long obj) {
        int l = 0, r = array.size() - 1;
        while (r - l >= 0) {
            int c = (l + r) / 2;
            if (obj <= array.get(c)) {
                r = c - 1;
            } else {
                l = c + 1;
            }
        }
        return l;
    }
    static <T> T[][] deepCopy(T[][] matrix) { return Arrays.stream(matrix).map(el -> el.clone()).toArray($ -> matrix.clone()); }
    static int[][] deepCopy(int[][] matrix) { return Arrays.stream(matrix).map(int[]::clone).toArray($ -> matrix.clone()); }
    static long[][] deepCopy(long[][] matrix) { return Arrays.stream(matrix).map(long[]::clone).toArray($ -> matrix.clone()); }
    private static void sort(int[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); }
    private static void sort(long[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); }
    private static <T>void rSort(T[] arr) { Arrays.sort(arr, Collections.reverseOrder()); }
    private static void customSort(int[][] arr) {
        Arrays.sort(arr, new Comparator<int[]>() {
            public int compare(int[] a, int[] b) {
                if (a[0] == b[0]) return Integer.compare(a[1], b[1]);
                return Integer.compare(a[0], b[0]);
            }
        });
    }
    public static int[] swap(int[] arr, int left, int right) {
        int temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;
        return arr;
    }
    public static char[] swap(char[] arr, int left, int right) {
        char temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;
        return arr;
    }
    public static int[] reverse(int[] arr, int left, int right) {
        while (left < right) {
            int temp = arr[left];
            arr[left++] = arr[right];
            arr[right--] = temp;
        }
        return arr;
    }
    public static boolean findNextPermutation(int[] data) {
        if (data.length <= 1) return false;
        int last = data.length - 2;
        while (last >= 0) {
            if (data[last] < data[last + 1]) break;
            last--;
        }
        if (last < 0) return false;
        int nextGreater = data.length - 1;
        for (int i = data.length - 1; i > last; i--) {
            if (data[i] > data[last]) {
                nextGreater = i;
                break;
            }
        }
        data = swap(data, nextGreater, last);
        data = reverse(data, last + 1, data.length - 1);
        return true;
    }
    public static int biSearch(int[] dt, int target){
        int left=0, right=dt.length-1;
        int mid=-1;
        while(left<=right){
            mid = (right+left)/2;
            if(dt[mid] == target) return mid;
            if(dt[mid] < target) left=mid+1;
            else right=mid-1;
        }
        return -1;
    }
    public static int biSearchMax(long[] dt, long target){
        int left=-1, right=dt.length;
        int mid=-1;

        while((right-left)>1){
            mid = left + (right-left)/2;
            if(dt[mid] <= target) left=mid;
            else right=mid;
        }
        return left;
    }
    public static int biSearchMaxAL(ArrayList<Integer> dt, long target){
        int left=-1, right=dt.size();
        int mid=-1;

        while((right-left)>1){
            mid = left + (right-left)/2;
            if(dt.get(mid) <= target) left=mid;
            else right=mid;
        }
        return left;
    }
    private static <T>void fill(T[][] ob, T res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}
    private static void fill(boolean[][] ob,boolean res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}
    private static void fill(int[][] ob, int res){      for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}
    private static void fill(long[][] ob, long res){    for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}
    private static void fill(char[][] ob, char res){    for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}
    private static void fill(double[][] ob, double res){for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}
    private static void fill(int[][][] ob,int res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}
    private static void fill(long[][][] ob,long res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}
    private static <T>void fill(T[][][] ob,T res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}
    private static void fill_parent(int[] ob){ for(int i=0; i<ob.length; i++) ob[i]=i; }
    private static boolean same3(long a, long b, long c){
        if(a!=b) return false;
        if(b!=c) return false;
        if(c!=a) return false;
        return true;
    }
    private static boolean dif3(long a, long b, long c){
        if(a==b) return false;
        if(b==c) return false;
        if(c==a) return false;
        return true;
    }
    private static double hypotenuse(double a, double b){
        return Math.sqrt(a*a+b*b);
    }
    private static long factorial(int n) {
        long ans=1;
        for(long i=n; i>0; i--){ ans*=i; }
        return ans;
    }
    private static long facMod(int n, long mod) {
        long ans=1;
        for(long i=n; i>0; i--) ans = (ans * i) % mod;
        return ans;
    }
    private static long lcm(long m, long n){
        long ans = m/gcd(m,n);
        ans *= n;
        return ans;
    }
    private static long gcd(long m, long n) {
        if(m < n) return gcd(n, m);
        if(n == 0) return m;
        return gcd(n, m % n);
    }
    private static boolean isPrime(long a){
        if(a==1) return false;
        for(int i=2; i<=Math.sqrt(a); i++){  if(a%i == 0) return false;  }
        return true;
    }
    static long modInverse(long a, long mod) {
    /* Fermat's little theorem: a^(MOD-1) => 1
    Therefore (divide both sides by a): a^(MOD-2) => a^(-1) */
        return binpowMod(a, mod - 2, mod);
    }
    static long binpowMod(long a, long b, long mod) {
        long res = 1;
        while (b > 0) {
            if (b % 2 == 1) res = (res * a) % mod;
            a = (a * a) % mod;
            b /= 2;
        }
        return res;
    }
    private static int getDigit2(long num){
        long cf = 1;    int d=0;
        while(num >= cf){   d++;    cf = 1<<d;  }
        return d;
    }
    private static int getDigit10(long num){
        long cf = 1;    int d=0;
        while(num >= cf){   d++;    cf*=10;     }
        return d;
    }
    private static boolean isInArea(int y, int x, int h, int w){
        if(y<0) return false;
        if(x<0) return false;
        if(y>=h) return false;
        if(x>=w) return false;
        return true;
    }
    private static ArrayList<Integer> generatePrimes(int n) {
        int[] lp = new int[n + 1];
        ArrayList<Integer> pr = new ArrayList<>();
        for (int i = 2; i <= n; ++i) {
            if (lp[i] == 0) {
                lp[i] = i;
                pr.add(i);
            }
            for (int j = 0; j < pr.size() && pr.get(j) <= lp[i] && i * pr.get(j) <= n; ++j) {
                lp[i * pr.get(j)] = pr.get(j);
            }
        }
        return pr;
    }
    static long nPrMod(int n, int r, long MOD) {
        long res = 1;
        for (int i = (n - r + 1); i <= n; i++) {
            res = (res * i) % MOD;
        }
        return res;
    }
    static long nCr(int n, int r) {
        if (r > (n - r))
            r = n - r;
        long ans = 1;
        for (int i = 1; i <= r; i++) {
            ans *= n;
            ans /= i;
            n--;
        }
        return ans;
    }
    static long nCrMod(int n, int r, long MOD) {
        long rFactorial = nPrMod(r, r, MOD);
        long first = nPrMod(n, r, MOD);
        long second = binpowMod(rFactorial, MOD-2, MOD);
        return  (first * second) % MOD;
    }
    static void printBitRepr(int n) {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < 32; i++) {
            int mask = (1 << i);
            res.append((mask & n) == 0 ? "0" : "1");
        }
        out.println(res);
    }
    static String bitString(int n) {return Integer.toBinaryString(n);}
    static int setKthBitToOne(int n, int k) { return (n | (1 << k)); } // zero indexed
    static int setKthBitToZero(int n, int k) { return (n & ~(1 << k)); }
    static int invertKthBit(int n, int k) { return (n ^ (1 << k)); }
    static boolean isPowerOfTwo(int n) { return (n & (n - 1)) == 0; }
    static HashMap<Character, Integer> counts(String word) {
        HashMap<Character, Integer> counts = new HashMap<>();
        for (int i = 0; i < word.length(); i++) counts.merge(word.charAt(i), 1, Integer::sum);
        return counts;
    }
    static HashMap<Integer, Integer> counts(int[] arr) {
        HashMap<Integer, Integer> counts = new HashMap<>();
        for (int value : arr) counts.merge(value, 1, Integer::sum);
        return counts;
    }
    static HashMap<Long, Integer> counts(long[] arr) {
        HashMap<Long, Integer> counts = new HashMap<>();
        for (long l : arr) counts.merge(l, 1, Integer::sum);
        return counts;
    }
    static HashMap<Character, Integer> counts(char[] arr) {
        HashMap<Character, Integer> counts = new HashMap<>();
        for (char c : arr) counts.merge(c, 1, Integer::sum);
        return counts;
    }
    static long hash(int x, int y) {
        return x* 1_000_000_000L +y;
    }
    static final Random random = new Random();
    static void sort(int[] a) {
        int n = a.length;// shuffle, then sort
        for (int i = 0; i < n; i++) {
            int oi = random.nextInt(n), temp = a[oi];
            a[oi] = a[i];
            a[i] = temp;
        }
        Arrays.sort(a);
    }
    static void sort(long[] arr) {
        shuffleArray(arr);
        Arrays.sort(arr);
    }
    static void shuffleArray(long[] arr) {
        int n = arr.length;
        for(int i=0; i<n; ++i){
            long tmp = arr[i];
            int randomPos = i + random.nextInt(n-i);
            arr[i] = arr[randomPos];
            arr[randomPos] = tmp;
        }
    }
}
static class Tuple implements Comparable<Tuple> {
    int a;
    int b;
    int c;
    public Tuple(int a, int b) {
        this.a = a;
        this.b = b;
        this.c = 0;
    }
    public Tuple(int a, int b, int c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }
    public int getA() { return a; }
    public int getB() { return b; }
    public int getC() { return c; }
    public int compareTo(Tuple other) {
        if (this.a == other.a) {
            if (this.b == other.b) return Long.compare(this.c, other.c);
            return Long.compare(this.b, other.b);
        }
        return Long.compare(this.a, other.a);
    }
    @Override
    public int hashCode() { return Arrays.deepHashCode(new Integer[]{a, b, c}); }
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Tuple)) return false;
        Tuple pairo = (Tuple) o;
        return (this.a == pairo.a && this.b == pairo.b && this.c == pairo.c);
    }
    @Override
    public String toString() { return String.format("(%d %d %d)  ", this.a, this.b, this.c); }
}
private static int abs(int a){  return (a>=0) ? a: -a;  }
private static int min(int... ins){ int min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }
private static int max(int... ins){ int max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }
private static int sum(int... ins){ int total = 0; for (int v : ins) { total += v; } return total; }
private static long abs(long a){    return (a>=0) ? a: -a;  }
private static long min(long... ins){ long min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }
private static long max(long... ins){ long max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }
private static long sum(long... ins){ long total = 0; for (long v : ins) { total += v; } return total; }
private static double abs(double a){    return (a>=0) ? a: -a;  }
private static double min(double... ins){ double min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }
private static double max(double... ins){ double max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }
private static double sum(double... ins){ double total = 0; for (double v : ins) { total += v; } return total; }

}

import java.io.*;
import java.math.BigInteger;
import java.util.*;

public class test {
	public static void main(String[] args) throws IOException {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		PrintWriter out = new PrintWriter(outputStream);
		InputReader in = new InputReader(inputStream);

//		for(int i=4;i<=4;i++) {
//			InputStream uinputStream = new FileInputStream("leftout.in");
//			String f = i+".in";
//			InputStream uinputStream = new FileInputStream(f);
//			InputReader in = new InputReader(uinputStream);
//			PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("leftout.out")));
			Task t = new Task();
			t.solve(in, out);
			out.close();
//		}
	}

	static class Task {

		public void solve(InputReader in, PrintWriter out) throws IOException {
//			Dumper.print(Long.MAX_VALUE);
//			int n = in.nextInt();
//			long a[] = new long[n];
//			for(int i=0;i<n;i++) {
//				a[i] = in.nextLong();
//			}
//			pair c[] = new pair[n];
//			for(int i=0;i<n;i++) {
//				a[i] *= (i+1)*(n-i);
//				c[i] = new pair(-1*a[i],i);
//			}
//			Arrays.sort(c);
//
//			long b[] = new long[n];
//			long d[] = new long[n];
//			for(int i=0;i<n;i++) {
//				d[i] = in.nextLong();
//			}
//			ArrayUtils.sort(d);
//			for(int i=0;i<n;i++) {
//				b[c[i].idx] = d[i];
//			}
//			long f = 998244353;
//			long ret[] = new long[n];
//			for(int i=n-1;i>=0;i--) {
//				ret[i]=a[i];
//				ret[i]%=f;
//				ret[i]*=b[i];
//				ret[i]%=f;
//			}
//			long v = 0;
//			for(long tmp:ret) {
//				v+=tmp;
//				v%=f;
//			}
//			out.println(v);
			int n = in.nextInt();
			int m = in.nextInt();
			int s = 0;
			int need[] = new int[n+1];
			for(int i=1;i<=n;i++) {
				need[i] = in.nextInt();
				s+=need[i];
			}
			Set<Integer>[] g = new HashSet[n+1];
			for(int i=1;i<=n;i++) g[i] = new HashSet<Integer>();
			for(int i=0;i<m;i++) {
				int d = in.nextInt();
				int t = in.nextInt();
				g[d].add(t);
			}

			int l = 1;
			int r = 1000;
			while(l<r-1) {
				int mid = l+(r-l)/2;
				if(is_ok(g,mid,need,s)) {
					r=mid;
				}else {
					l=mid;
				}
			}
			if(is_ok(g,l,need,s)) out.println(l);
			out.println(r);
		}
		boolean is_ok(Set<Integer>[] g, int mid, int need[], int all) {
			int offer[] = new int[need.length];
			for(int i=1;i<=Math.min(mid, g.length-1);i++) {
				for(int j:g[i]) offer[j] = i;
			}
			ArrayList<offer> arr = new ArrayList<offer>();
			for(int i=1;i<offer.length;i++) {
				if(offer[i]!=0) arr.add(new offer(i,offer[i]));
			}
			Collections.sort(arr);
			int temp[] = need.clone();
			if(arr.size()==0) return mid>=2*all;
			int cur = 0; int p=0;
			for(int i=1;i<=mid;i++) {
				cur++;
				while(p<arr.size()&&i==arr.get(p).day) {
					int item = arr.get(p).item;
					int num = temp[item];
					if(cur>=num) {
						cur-=num;
						all-=num;
						temp[item]=0;
					}else if(cur<num) {
						temp[item]-=cur;
						all-=cur;
						cur=0;
					}
					p++;
				}
			}
			return cur>=2*all;
		}
		class offer implements Comparable<offer>{
			int item; int day;
			public offer(int a, int b) {
				item = a; day=b;
			}
			@Override
			public int compareTo(offer t) {
				return this.day-t.day;
			}
		}
		class pair implements Comparable<pair>{
			Long val; int idx;
			public pair(long a, int b) {
				val=a;idx=b;
			}
			@Override
			public int compareTo(pair t) {
				return this.val.compareTo(t.val);
			}
		}
		boolean is_prime(int a) {
			if(a==2||a==3) return true;
			for(int i=2;i<=Math.sqrt(a);i++) {
				if(a%i==0) return false;
			}
			return true;
		}

		class TreeNode {
			int val;
			TreeNode left;
			TreeNode right;
			TreeNode(int x) { val = x; }
		}

		public int GCD(int a, int b) {
		   if (b==0) return a;
		   return GCD(b,a%b);
		}
	}

    static class ArrayUtils {
        static final long seed = System.nanoTime();
        static final Random rand = new Random(seed);

        public static void sort(int[] a) {
            shuffle(a);
            Arrays.sort(a);
        }

        public static void shuffle(int[] a) {
            for (int i = 0; i < a.length; i++) {
                int j = rand.nextInt(i + 1);
                int t = a[i];
                a[i] = a[j];
                a[j] = t;
            }
        }

        public static void sort(long[] a) {
            shuffle(a);
            Arrays.sort(a);
        }

        public static void shuffle(long[] a) {
            for (int i = 0; i < a.length; i++) {
                int j = rand.nextInt(i + 1);
                long t = a[i];
                a[i] = a[j];
                a[j] = t;
            }
        }

    }
	static class BIT{
		int arr[];
		int n;
		public BIT(int a) {
			n=a;
			arr = new int[n];
		}
		int sum(int p) {
			int s=0;
			while(p>0) {
				s+=arr[p];
				p-=p&(-p);
			}
			return s;
		}
		void add(int p, int v) {
			while(p<n) {
				arr[p]+=v;
				p+=p&(-p);
			}
		}
	}
	static class DSU{
		int[] arr;
		int[] sz;
		public DSU(int n) {
			arr = new int[n];
			sz = new int[n];
			for(int i=0;i<n;i++) arr[i] = i;
			Arrays.fill(sz, 1);
		}
		public int find(int a) {
			if(arr[a]!=a) arr[a] = find(arr[a]);
			return arr[a];
		}
		public void union(int a, int b) {
			int x = find(a);
			int y = find(b);
			if(x==y) return;
			arr[x] = y;
			sz[y] += sz[x];
		}
		public int size(int x) {
			return sz[find(x)];
		}
	}
	static class MinHeap<Key> implements Iterable<Key> {
		private int maxN;
		private int n;
		private int[] pq;
		private int[] qp;
		private Key[] keys;
		private Comparator<Key> comparator;

		public MinHeap(int capacity){
			if (capacity < 0) throw new IllegalArgumentException();
			this.maxN = capacity;
			n=0;
			pq = new int[maxN+1];
			qp = new int[maxN+1];
			keys = (Key[]) new Object[capacity+1];
			Arrays.fill(qp, -1);
		}

		public MinHeap(int capacity, Comparator<Key> c){
			if (capacity < 0) throw new IllegalArgumentException();
			this.maxN = capacity;
			n=0;
			pq = new int[maxN+1];
			qp = new int[maxN+1];
			keys = (Key[]) new Object[capacity+1];
			Arrays.fill(qp, -1);
			comparator = c;
		}
		public boolean isEmpty()	{ return n==0; 	}
		public int size()			{ return n;		}
		public boolean contains(int i) {
	        if (i < 0 || i >= maxN) throw new IllegalArgumentException();
	        return qp[i] != -1;
		}
		public int peekIdx() {
	        if (n == 0) throw new NoSuchElementException("Priority queue underflow");
	        return pq[1];
		}
		public Key peek(){
			if(isEmpty()) throw new NoSuchElementException("Priority queue underflow");
			return keys[pq[1]];
		}
		public int poll(){
			if(isEmpty()) throw new NoSuchElementException("Priority queue underflow");
			int min = pq[1];
			exch(1,n--);
			down(1);
			assert min==pq[n+1];
			qp[min] = -1;
			keys[min] = null;
			pq[n+1] = -1;
			return min;
		}
	    public void update(int i, Key key) {
	        if (i < 0 || i >= maxN) throw new IllegalArgumentException();
	        if (!contains(i)) {
	        	this.add(i, key);
	        }else {
	        	keys[i] = key;
	        	up(qp[i]);
	        	down(qp[i]);
	        }
	    }
		private void add(int i, Key x){
	        if (i < 0 || i >= maxN) throw new IllegalArgumentException();
	        if (contains(i)) throw new IllegalArgumentException("index is already in the priority queue");
	        n++;
	        qp[i] = n;
	        pq[n] = i;
	        keys[i] = x;
	        up(n);
		}
		private void up(int k){
			while(k>1&&less(k,k/2)){
				exch(k,k/2);
				k/=2;
			}
		}
		private void down(int k){
			while(2*k<=n){
				int j=2*k;
				if(j<n&&less(j+1,j)) j++;
				if(less(k,j)) break;
				exch(k,j);
				k=j;
			}
		}

		public boolean less(int i, int j){
	        if (comparator == null) {
	            return ((Comparable<Key>) keys[pq[i]]).compareTo(keys[pq[j]]) < 0;
	        }
	        else {
	            return comparator.compare(keys[pq[i]], keys[pq[j]]) < 0;
	        }
		}

		public void exch(int i, int j){
	        int swap = pq[i];
	        pq[i] = pq[j];
	        pq[j] = swap;
	        qp[pq[i]] = i;
	        qp[pq[j]] = j;
		}

		@Override
		public Iterator<Key> iterator() {
			// TODO Auto-generated method stub
			return null;
		}
	}

    private static class InputReader
    {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int zcurChar;
        private int znumChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream)
        {
            this.stream = stream;
        }

        public int read()
        {
            if (znumChars == -1)
                throw new InputMismatchException();
            if (zcurChar >= znumChars)
            {
            	zcurChar = 0;
                try
                {
                    znumChars = stream.read(buf);
                } catch (IOException e)
                {
                    throw new InputMismatchException();
                }
                if (znumChars <= 0)
                    return -1;
            }
            return buf[zcurChar++];
        }

        public int nextInt()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public String nextString()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public double nextDouble()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.')
            {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.')
            {
                c = read();
                double m = 1;
                while (!isSpaceChar(c))
                {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public long nextLong()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c)
        {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next()
        {
            return nextString();
        }

        public interface SpaceCharFilter
        {
            public boolean isSpaceChar(int ch);
        }
        public int[] readIntArray(int n) {
            int[] ret = new int[n];
            for (int i = 0; i < n; i++) {
                ret[i] = nextInt();
            }
            return ret;
        }
    }

	static class Dumper {
		static void print_int_arr(int[] arr) {
			for (int i = 0; i < arr.length; i++) {
				System.out.print(arr[i] + " ");
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print_char_arr(char[] arr) {
			for (int i = 0; i < arr.length; i++) {
				System.out.print(arr[i] + " ");
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print_double_arr(double[] arr) {
			for (int i = 0; i < arr.length; i++) {
				System.out.print(arr[i] + " ");
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print_2d_arr(int[][] arr, int x, int y) {
			for (int i = 0; i < x; i++) {
				for (int j = 0; j < y; j++) {
					System.out.print(arr[i][j] + " ");
				}
				System.out.println();
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print_2d_arr(boolean[][] arr, int x, int y) {
			for (int i = 0; i < x; i++) {
				for (int j = 0; j < y; j++) {
					System.out.print(arr[i][j] + " ");
				}
				System.out.println();
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print(Object o) {
			System.out.println(o.toString());
		}

		static void getc() {
			System.out.println("here");
		}
	}
}

import java.io.*;
import java.math.BigInteger;
import java.util.*;

public class test {
	public static void main(String[] args) throws IOException {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		PrintWriter out = new PrintWriter(outputStream);
		InputReader in = new InputReader(inputStream);

//		for(int i=4;i<=4;i++) {
//			InputStream uinputStream = new FileInputStream("leftout.in");
//			String f = i+".in";
//			InputStream uinputStream = new FileInputStream(f);
//			InputReader in = new InputReader(uinputStream);
//			PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("leftout.out")));
			Task t = new Task();
			t.solve(in, out);
			out.close();
//		}
	}

	static class Task {

		public void solve(InputReader in, PrintWriter out) throws IOException {
//			Dumper.print(Long.MAX_VALUE);
//			int n = in.nextInt();
//			long a[] = new long[n];
//			for(int i=0;i<n;i++) {
//				a[i] = in.nextLong();
//			}
//			pair c[] = new pair[n];
//			for(int i=0;i<n;i++) {
//				a[i] *= (i+1)*(n-i);
//				c[i] = new pair(-1*a[i],i);
//			}
//			Arrays.sort(c);
//
//			long b[] = new long[n];
//			long d[] = new long[n];
//			for(int i=0;i<n;i++) {
//				d[i] = in.nextLong();
//			}
//			ArrayUtils.sort(d);
//			for(int i=0;i<n;i++) {
//				b[c[i].idx] = d[i];
//			}
//			long f = 998244353;
//			long ret[] = new long[n];
//			for(int i=n-1;i>=0;i--) {
//				ret[i]=a[i];
//				ret[i]%=f;
//				ret[i]*=b[i];
//				ret[i]%=f;
//			}
//			long v = 0;
//			for(long tmp:ret) {
//				v+=tmp;
//				v%=f;
//			}
//			out.println(v);
			int n = in.nextInt();
			int m = in.nextInt();
			int s = 0;
			int need[] = new int[n+1];
			for(int i=1;i<=n;i++) {
				need[i] = in.nextInt();
				s+=need[i];
			}
			Set<Integer>[] g = new HashSet[n+1];
			for(int i=1;i<=n;i++) g[i] = new HashSet<Integer>();
			for(int i=0;i<m;i++) {
				int d = in.nextInt();
				int t = in.nextInt();
				g[d].add(t);
			}

			int l = 1;
			int r = 2002;
			while(l<r-1) {
				int mid = l+(r-l)/2;
				if(is_ok(g,mid,need,s)) {
					r=mid;
				}else {
					l=mid;
				}
			}
			if(is_ok(g,l,need,s)) out.println(l);
			out.println(r);
		}
		boolean is_ok(Set<Integer>[] g, int mid, int need[], int all) {
			int offer[] = new int[need.length];
			for(int i=1;i<=Math.min(mid, g.length-1);i++) {
				for(int j:g[i]) offer[j] = i;
			}
			ArrayList<offer> arr = new ArrayList<offer>();
			for(int i=1;i<offer.length;i++) {
				if(offer[i]!=0) arr.add(new offer(i,offer[i]));
			}
			Collections.sort(arr);
			int temp[] = need.clone();
			if(arr.size()==0) return mid>=2*all;
			int cur = 0; int p=0;
			for(int i=1;i<=mid;i++) {
				cur++;
				while(p<arr.size()&&i==arr.get(p).day) {
					int item = arr.get(p).item;
					int num = temp[item];
					if(cur>=num) {
						cur-=num;
						all-=num;
						temp[item]=0;
					}else if(cur<num) {
						temp[item]-=cur;
						all-=cur;
						cur=0;
					}
					p++;
				}
			}
			return cur>=2*all;
		}
		class offer implements Comparable<offer>{
			int item; int day;
			public offer(int a, int b) {
				item = a; day=b;
			}
			@Override
			public int compareTo(offer t) {
				return this.day-t.day;
			}
		}
		class pair implements Comparable<pair>{
			Long val; int idx;
			public pair(long a, int b) {
				val=a;idx=b;
			}
			@Override
			public int compareTo(pair t) {
				return this.val.compareTo(t.val);
			}
		}
		boolean is_prime(int a) {
			if(a==2||a==3) return true;
			for(int i=2;i<=Math.sqrt(a);i++) {
				if(a%i==0) return false;
			}
			return true;
		}

		class TreeNode {
			int val;
			TreeNode left;
			TreeNode right;
			TreeNode(int x) { val = x; }
		}

		public int GCD(int a, int b) {
		   if (b==0) return a;
		   return GCD(b,a%b);
		}
	}

    static class ArrayUtils {
        static final long seed = System.nanoTime();
        static final Random rand = new Random(seed);

        public static void sort(int[] a) {
            shuffle(a);
            Arrays.sort(a);
        }

        public static void shuffle(int[] a) {
            for (int i = 0; i < a.length; i++) {
                int j = rand.nextInt(i + 1);
                int t = a[i];
                a[i] = a[j];
                a[j] = t;
            }
        }

        public static void sort(long[] a) {
            shuffle(a);
            Arrays.sort(a);
        }

        public static void shuffle(long[] a) {
            for (int i = 0; i < a.length; i++) {
                int j = rand.nextInt(i + 1);
                long t = a[i];
                a[i] = a[j];
                a[j] = t;
            }
        }

    }
	static class BIT{
		int arr[];
		int n;
		public BIT(int a) {
			n=a;
			arr = new int[n];
		}
		int sum(int p) {
			int s=0;
			while(p>0) {
				s+=arr[p];
				p-=p&(-p);
			}
			return s;
		}
		void add(int p, int v) {
			while(p<n) {
				arr[p]+=v;
				p+=p&(-p);
			}
		}
	}
	static class DSU{
		int[] arr;
		int[] sz;
		public DSU(int n) {
			arr = new int[n];
			sz = new int[n];
			for(int i=0;i<n;i++) arr[i] = i;
			Arrays.fill(sz, 1);
		}
		public int find(int a) {
			if(arr[a]!=a) arr[a] = find(arr[a]);
			return arr[a];
		}
		public void union(int a, int b) {
			int x = find(a);
			int y = find(b);
			if(x==y) return;
			arr[x] = y;
			sz[y] += sz[x];
		}
		public int size(int x) {
			return sz[find(x)];
		}
	}
	static class MinHeap<Key> implements Iterable<Key> {
		private int maxN;
		private int n;
		private int[] pq;
		private int[] qp;
		private Key[] keys;
		private Comparator<Key> comparator;

		public MinHeap(int capacity){
			if (capacity < 0) throw new IllegalArgumentException();
			this.maxN = capacity;
			n=0;
			pq = new int[maxN+1];
			qp = new int[maxN+1];
			keys = (Key[]) new Object[capacity+1];
			Arrays.fill(qp, -1);
		}

		public MinHeap(int capacity, Comparator<Key> c){
			if (capacity < 0) throw new IllegalArgumentException();
			this.maxN = capacity;
			n=0;
			pq = new int[maxN+1];
			qp = new int[maxN+1];
			keys = (Key[]) new Object[capacity+1];
			Arrays.fill(qp, -1);
			comparator = c;
		}
		public boolean isEmpty()	{ return n==0; 	}
		public int size()			{ return n;		}
		public boolean contains(int i) {
	        if (i < 0 || i >= maxN) throw new IllegalArgumentException();
	        return qp[i] != -1;
		}
		public int peekIdx() {
	        if (n == 0) throw new NoSuchElementException("Priority queue underflow");
	        return pq[1];
		}
		public Key peek(){
			if(isEmpty()) throw new NoSuchElementException("Priority queue underflow");
			return keys[pq[1]];
		}
		public int poll(){
			if(isEmpty()) throw new NoSuchElementException("Priority queue underflow");
			int min = pq[1];
			exch(1,n--);
			down(1);
			assert min==pq[n+1];
			qp[min] = -1;
			keys[min] = null;
			pq[n+1] = -1;
			return min;
		}
	    public void update(int i, Key key) {
	        if (i < 0 || i >= maxN) throw new IllegalArgumentException();
	        if (!contains(i)) {
	        	this.add(i, key);
	        }else {
	        	keys[i] = key;
	        	up(qp[i]);
	        	down(qp[i]);
	        }
	    }
		private void add(int i, Key x){
	        if (i < 0 || i >= maxN) throw new IllegalArgumentException();
	        if (contains(i)) throw new IllegalArgumentException("index is already in the priority queue");
	        n++;
	        qp[i] = n;
	        pq[n] = i;
	        keys[i] = x;
	        up(n);
		}
		private void up(int k){
			while(k>1&&less(k,k/2)){
				exch(k,k/2);
				k/=2;
			}
		}
		private void down(int k){
			while(2*k<=n){
				int j=2*k;
				if(j<n&&less(j+1,j)) j++;
				if(less(k,j)) break;
				exch(k,j);
				k=j;
			}
		}

		public boolean less(int i, int j){
	        if (comparator == null) {
	            return ((Comparable<Key>) keys[pq[i]]).compareTo(keys[pq[j]]) < 0;
	        }
	        else {
	            return comparator.compare(keys[pq[i]], keys[pq[j]]) < 0;
	        }
		}

		public void exch(int i, int j){
	        int swap = pq[i];
	        pq[i] = pq[j];
	        pq[j] = swap;
	        qp[pq[i]] = i;
	        qp[pq[j]] = j;
		}

		@Override
		public Iterator<Key> iterator() {
			// TODO Auto-generated method stub
			return null;
		}
	}

    private static class InputReader
    {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int zcurChar;
        private int znumChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream)
        {
            this.stream = stream;
        }

        public int read()
        {
            if (znumChars == -1)
                throw new InputMismatchException();
            if (zcurChar >= znumChars)
            {
            	zcurChar = 0;
                try
                {
                    znumChars = stream.read(buf);
                } catch (IOException e)
                {
                    throw new InputMismatchException();
                }
                if (znumChars <= 0)
                    return -1;
            }
            return buf[zcurChar++];
        }

        public int nextInt()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public String nextString()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public double nextDouble()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.')
            {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.')
            {
                c = read();
                double m = 1;
                while (!isSpaceChar(c))
                {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public long nextLong()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c)
        {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next()
        {
            return nextString();
        }

        public interface SpaceCharFilter
        {
            public boolean isSpaceChar(int ch);
        }
        public int[] readIntArray(int n) {
            int[] ret = new int[n];
            for (int i = 0; i < n; i++) {
                ret[i] = nextInt();
            }
            return ret;
        }
    }

	static class Dumper {
		static void print_int_arr(int[] arr) {
			for (int i = 0; i < arr.length; i++) {
				System.out.print(arr[i] + " ");
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print_char_arr(char[] arr) {
			for (int i = 0; i < arr.length; i++) {
				System.out.print(arr[i] + " ");
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print_double_arr(double[] arr) {
			for (int i = 0; i < arr.length; i++) {
				System.out.print(arr[i] + " ");
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print_2d_arr(int[][] arr, int x, int y) {
			for (int i = 0; i < x; i++) {
				for (int j = 0; j < y; j++) {
					System.out.print(arr[i][j] + " ");
				}
				System.out.println();
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print_2d_arr(boolean[][] arr, int x, int y) {
			for (int i = 0; i < x; i++) {
				for (int j = 0; j < y; j++) {
					System.out.print(arr[i][j] + " ");
				}
				System.out.println();
			}
			System.out.println();
			System.out.println("---------------------");
		}

		static void print(Object o) {
			System.out.println(o.toString());
		}

		static void getc() {
			System.out.println("here");
		}
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.TreeSet;
import java.util.HashSet;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        Task1165F solver = new Task1165F();
        solver.solve(1, in, out);
        out.close();
    }

    static class Task1165F {
        HashMap<Integer, HashSet<Integer>> hm;
        TreeSet<Integer> days;

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            int arr[] = new int[n];
            hm = new HashMap<>();
            days = new TreeSet<>();
            int i, j, sum = 0;

            for (i = 0; i < n; i++) {
                arr[i] = in.nextInt();
                sum += arr[i];
            }

            for (i = 0; i < m; i++) {
                int d = in.nextInt();
                int t = in.nextInt() - 1;
                days.add(d);
                if (hm.get(d) == null) {
                    HashSet<Integer> hs = new HashSet<>();
                    hs.add(t);
                    hm.put(d, hs);
                } else {
                    HashSet<Integer> hs = hm.get(d);
                    hs.add(t);
                    hm.put(d, hs);
                }
            }

            for (i = sum; i <= 2 * sum; i++) {
                int cur = check(arr, n, i, sum);
                if (cur == 0)
                    break;
            }
            out.println(i);

        }

        int check(int arra[], int n, int i, int suma) {
            int arr[] = Arrays.copyOf(arra, n);
            int sum = suma;
            int total_money = i;
            int cur_money = 0;
            int prev = 0;
            for (int k : days) {
                if (k > i)
                    break;

                HashSet<Integer> hs = hm.get(k);
                cur_money += k - prev;
                prev = k;
                //System.out.println(cur_money);
                for (int l : hs) {
                    if (cur_money == 0)
                        break;
                    int val = Math.min(cur_money, arr[l]);
                    cur_money -= val;
                    arr[l] -= val;
                    sum -= val;
                    // System.out.println("spec" + val + " " + sum);
                }
            }
            cur_money += i - prev;
            //System.out.println(i + " " + cur_money + " " + sum);
            cur_money /= 2;
            sum -= cur_money;
            sum = Math.max(sum, 0);
            return sum;
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void println(int i) {
            writer.println(i);
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;
import java.util.Map;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        Task1165F solver = new Task1165F();
        solver.solve(1, in, out);
        out.close();
    }

    static class Task1165F {
        ArrayList<Pair<Integer, Integer>> al = new ArrayList<>();

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            int arr[] = new int[n];
            int i, j, sum = 0;

            for (i = 0; i < n; i++) {
                arr[i] = in.nextInt();
                sum += arr[i];
            }

            for (i = 0; i < m; i++) {
                int d = in.nextInt();
                int t = in.nextInt() - 1;
                al.add(new Pair(d, t));
            }

            for (i = sum; i <= 2 * sum; i++) {
                int cur = check(arr, n, i, sum);
                if (cur == 0)
                    break;
            }

            out.println(i);

        }

        int check(int arra[], int n, int total_money, int suma) {
            int arr[] = Arrays.copyOf(arra, n);
            int sum = suma;
            int day[] = new int[n];

            int i, j;
            for (Pair t : al) {
                int first = (int) t.getFirst();
                int second = (int) t.getSecond();
                if (first > total_money)
                    continue;
                day[second] = Math.max(day[second], first);
            }

            TreeMap<Integer, Integer> tm = new TreeMap<>();
            for (i = 0; i < n; i++) {
                if (day[i] != 0) {
                    tm.put(day[i], tm.getOrDefault(day[i], 0) + arr[i]);
                }
            }
            int cur_money = 0;
            for (i = 1; i <= total_money; i++) {
                cur_money++;
                int val = Math.min(tm.getOrDefault(i, 0), cur_money);
                cur_money -= val;
                sum -= val;
            }

            cur_money /= 2;
            sum -= cur_money;

            return sum;
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void println(int i) {
            writer.println(i);
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class Pair<A, B> {
        A first;
        B second;

        public Pair(A first, B second) {
            super();
            this.first = first;
            this.second = second;
        }

        public int hashCode() {
            int hashFirst = first != null ? first.hashCode() : 0;
            int hashSecond = second != null ? second.hashCode() : 0;

            return (hashFirst + hashSecond) * hashSecond + hashFirst;
        }

        public boolean equals(Object other) {
            if (other instanceof Pair) {
                Pair otherPair = (Pair) other;
                return
                        ((this.first == otherPair.first ||
                                (this.first != null && otherPair.first != null &&
                                        this.first.equals(otherPair.first))) &&
                                (this.second == otherPair.second ||
                                        (this.second != null && otherPair.second != null &&
                                                this.second.equals(otherPair.second))));
            }

            return false;
        }

        public String toString() {
            return "(" + first + ", " + second + ")";
        }

        public A getFirst() {
            return first;
        }

        public B getSecond() {
            return second;
        }

    }
}

import java.io.*;
import java.util.*;

public class ProblemF_1 {

    public static InputStream inputStream = System.in;

    public static OutputStream outputStream = System.out;

    public static void main(String[] args) {
        MyScanner scanner = new MyScanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);

        int n = scanner.nextInt();
        int m = scanner.nextInt();
        List<Integer> amounts = new ArrayList<>();
        int s = 0;
        for (int i = 0; i < n; i++) {
            int x = scanner.nextInt();
            s = s + x;
            amounts.add(x);
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < m; i++) {
            int d = scanner.nextInt();
            int t = scanner.nextInt();
            if (map.containsKey(t)) {
                if (map.get(t) < d) {
                    map.put(t, d);
                }
            } else {
                map.put(t, d);
            }
        }

        Map<Integer, List<Integer>> sales = new HashMap<>();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (!sales.containsKey(entry.getValue())) {
                sales.put(entry.getValue(), new ArrayList<>());
            }
            sales.get(entry.getValue()).add(entry.getKey());
        }

        int x = 0;
        int ans = 0;
        for (int i = 1; i <= 1000; i++) {
            x++;
            ans = i;
            if (sales.containsKey(i)) {
                for (int t : sales.get(i)) {
                    if (x > amounts.get(t - 1)) {
                        s = s - amounts.get(t - 1);
                        x = x - amounts.get(t - 1);
                    } else {
                        s = s - x;
                        x = 0;
                    }
                }
            }
            if (s * 2 <= x) {
                break;
            }
        }

        out.println(ans);

        out.flush();
    }

    private static class MyScanner {
        private BufferedReader bufferedReader;
        private StringTokenizer stringTokenizer;

        private MyScanner(InputStream inputStream) {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        }

        private String next() {
            while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) {
                try {
                    stringTokenizer = new StringTokenizer(bufferedReader.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return stringTokenizer.nextToken();
        }

        private int nextInt() {
            return Integer.parseInt(next());
        }

        private long nextLong() {
            return Long.parseLong(next());
        }

        private double nextDouble() {
            return Double.parseDouble(next());
        }

        private String nextLine() {
            String str = "";
            try {
                str = bufferedReader.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }

    private static class Pair<F, S> {

        private F first;

        private S second;

        public Pair() {
        }

        public Pair(F first, S second) {
            this.first = first;
            this.second = second;
        }
    }
}

import java.io.*;
import java.util.*;

public class ProblemF_1 {

    public static InputStream inputStream = System.in;

    public static OutputStream outputStream = System.out;

    public static void main(String[] args) {
        MyScanner scanner = new MyScanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);

        int n = scanner.nextInt();
        int m = scanner.nextInt();
        List<Integer> amounts = new ArrayList<>();
        int s = 0;
        for (int i = 0; i < n; i++) {
            int x = scanner.nextInt();
            s = s + x;
            amounts.add(x);
        }
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < m; i++) {
            int d = scanner.nextInt();
            int t = scanner.nextInt();
            if (!map.containsKey(d)) {
                map.put(d, new ArrayList<>());
            }
            map.get(d).add(t);
        }

        int x = 0;
        for (int i = 1; i <= 2000; i++) {
            x++;
            if (map.containsKey(i)) {
                for (int t : map.get(i)) {
                    if (amounts.get(t - 1) > 0) {
                        if (x > amounts.get(t - 1)) {
                            x = x - amounts.get(t - 1);
                            s = s - (amounts.get(t - 1));
                            amounts.set(t - 1, 0);
                        } else {
                            amounts.set(t - 1, amounts.get(t - 1) - x);
                            s = s - x;
                            x = 0;
                        }
                    }
                }
            }
            if (s == 0) {
                out.println(i);
                break;
            }
            if (x >= 2 * s) {
                out.println(i);
                break;
            }
        }

        out.flush();
    }

    private static class MyScanner {
        private BufferedReader bufferedReader;
        private StringTokenizer stringTokenizer;

        private MyScanner(InputStream inputStream) {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        }

        private String next() {
            while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) {
                try {
                    stringTokenizer = new StringTokenizer(bufferedReader.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return stringTokenizer.nextToken();
        }

        private int nextInt() {
            return Integer.parseInt(next());
        }

        private long nextLong() {
            return Long.parseLong(next());
        }

        private double nextDouble() {
            return Double.parseDouble(next());
        }

        private String nextLine() {
            String str = "";
            try {
                str = bufferedReader.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }

    private static class Pair<F, S> {

        private F first;

        private S second;

        public Pair() {
        }

        public Pair(F first, S second) {
            this.first = first;
            this.second = second;
        }
    }
}

import java.util.*;
public class Main {
    public static int n, m;
    public static int[] arr;
    public static TreeSet<Integer>[] set;
    public static boolean ok(int day) {
        int[] clone = arr.clone();
        int[] last = new int[n];
        for (int i = 0; i < n; i++) {
            Integer res = set[i].floor(day);
            last[i] = (res == null) ? -1 : res;
        }
        int burles = 0;
        for (int i = 0; i <= day; i++) {
            burles++;
            for (int j = 0; j < n; j++) {
                if (last[j] == i) {
                    while (clone[j] > 0 && burles > 0) {
                        burles--;
                        clone[j]--;
                    }
                }
            }
        }
        for (int i = 0; i < n; i++) {
            while (clone[i] > 0) {
                clone[i]--;
                burles -= 2;
            }
        }
        return burles >= 0;
    }
    public static void check(int l, int r) {
        if (r - l <= 5) {
            for (int i = l; i <= r; i++) {
                if (ok(i)) {
                    System.out.println(i + 1);
                    return;
                }
            }
            return;
        }
        int mid = (l + r) / 2;
        if (ok(mid)) {
            check(l, mid - 1);
        } else {
            check(mid + 1, r);
        }
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        m = in.nextInt();
        arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = in.nextInt();
        }
        set = new TreeSet[n];
        for (int i = 0; i < n; i++) {
            set[i] = new TreeSet<>();
        }
        for (int i = 0; i < m; i++) {
            int d = in.nextInt() - 1;
            int t = in.nextInt() - 1;
            set[t].add(d);
        }
        check(0, 1000000);
    }
}

import java.util.*;
public class Main {
    public static int n, m;
    public static int[] arr;
    public static TreeSet<Integer>[] set;
    public static boolean ok(int day) {
        int[] clone = arr.clone();
        int[] last = new int[n];
        for (int i = 0; i < n; i++) {
            Integer res = set[i].floor(day);
            last[i] = (res == null) ? -1 : res;
        }
        int burles = 0;
        for (int i = 0; i <= day; i++) {
            burles++;
            for (int j = 0; j < n; j++) {
                if (last[j] == i) {
                    while (clone[j] > 0 && burles > 0) {
                        burles--;
                        clone[j]--;
                    }
                }
            }
        }
        for (int i = 0; i < n; i++) {
            while (clone[i] > 0) {
                clone[i]--;
                burles -= 2;
            }
        }
        return burles >= 0;
    }
    public static void check(int l, int r) {
        if (r - l <= 5) {
            for (int i = l; i <= r; i++) {
                if (ok(i)) {
                    System.out.println(i + 1);
                    return;
                }
            }
            return;
        }
        int mid = (l + r) / 2;
        if (ok(mid)) {
            check(l, mid - 1);
        } else {
            check(mid + 1, r);
        }
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        m = in.nextInt();
        arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = in.nextInt();
        }
        set = new TreeSet[n];
        for (int i = 0; i < n; i++) {
            set[i] = new TreeSet<>();
        }
        for (int i = 0; i < m; i++) {
            int d = in.nextInt() - 1;
            int t = in.nextInt() - 1;
            set[t].add(d);
        }
        check(0, 2000);
    }
}

import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.TreeSet;

public class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int m = in.nextInt();

    int[] wanted = new int[n];
    int total = 0;

    for (int i = 0; i < n; i += 1) {
      wanted[i] = in.nextInt();
      total += wanted[i];
    }

    ArrayList<TreeSet<Integer>> discounted = new ArrayList<TreeSet<Integer>>();
    for (int i = 0; i < 2 * total; i += 1) {
      discounted.add(new TreeSet<Integer>());
    }

    for (int i = 0; i < m; i += 1) {
      int day = in.nextInt();
      int type = in.nextInt();
      if (day <= 2 * total) {
        discounted.get(day - 1).add(type - 1);
      }
    }

    ArrayList<ArrayList<Ticket>> tickets = new ArrayList<ArrayList<Ticket>>();
    for (int i = 0; i < 2 * total; i += 1) {
      tickets.add(new ArrayList<Ticket>());
    }

    int[] next = new int[n];
    Arrays.fill(next, 2 * total + 2);

    for (int i = 2 * total - 1; i >= 0; i -= 1) {
      for (int type : discounted.get(i)) {
        tickets.get(i).add(new Ticket(type, next[type]));
        next[type] = i;
      }
      Collections.sort(tickets.get(i));
    }

    boolean[] used = new boolean[2 * total];
    for (int i = 0; i < 2 * total; i += 1) {
      buyWanted(wanted, used, tickets.get(i), i);
    }

    total = 0;
    for (int num : wanted) {
      total += num;
    }

    boolean first = true;
    for (int i = 0; i < used.length && total > 0; i += 1) {
      if (!used[i]) {
        used[i] = true;
        if (!first) {
          total -= 1;
        }
        first = !first;
      }
    }

    System.out.println(findAnswer(used));
  }

  private static void buyWanted(int[] wanted, boolean[] used, ArrayList<Ticket> tickets, int day) {
    for (Ticket ticket : tickets) {
      for (int i = wanted[ticket.type]; i > 0; i -= 1) {
        int prevDay = findNotUsed(used, day);
        if (prevDay == -1) {
          break;
        }

        used[prevDay] = true;
        wanted[ticket.type] -= 1;
        day = prevDay;
      }
    }
  }

  private static int findNotUsed(boolean[] used, int startPos) {
    while (startPos >= 0) {
      if (!used[startPos]) {
        return startPos;
      }
      startPos -= 1;
    }
    return -1;
  }

  private static int findAnswer(final boolean[] used) {
    int res = 0;
    for (int i = 0; i < used.length; i += 1) {
      if (used[i]) {
        res = i;
      }
    }
    return res + 1;
  }
}

class Ticket implements Comparable<Ticket> {
  public int type;
  public int next;

  public Ticket(int type, int next) {
    this.type = type;
    this.next = next;
  }

  @Override
  public int compareTo(final Ticket other) {
    return other.next - next;
  }
}

import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.TreeSet;

public class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int m = in.nextInt();

    int[] wanted = new int[n];
    int total = 0;

    for (int i = 0; i < n; i += 1) {
      wanted[i] = in.nextInt();
      total += wanted[i];
    }

    ArrayList<TreeSet<Integer>> discounted = new ArrayList<TreeSet<Integer>>();
    for (int i = 0; i < 2 * total; i += 1) {
      discounted.add(new TreeSet<Integer>());
    }

    for (int i = 0; i < m; i += 1) {
      int day = in.nextInt();
      int type = in.nextInt();
      discounted.get(day - 1).add(type - 1);
    }

    ArrayList<ArrayList<Ticket>> tickets = new ArrayList<ArrayList<Ticket>>();
    for (int i = 0; i < 2 * total; i += 1) {
      tickets.add(new ArrayList<Ticket>());
    }

    int[] next = new int[n];
    Arrays.fill(next, 2 * total + 2);

    for (int i = 2 * total - 1; i >= 0; i -= 1) {
      for (int type : discounted.get(i)) {
        tickets.get(i).add(new Ticket(type, next[type]));
        next[type] = i;
      }
      Collections.sort(tickets.get(i));
    }

    boolean[] used = new boolean[2 * total];
    for (int i = 0; i < 2 * total; i += 1) {
      buyWanted(wanted, used, tickets.get(i), i);
    }

    total = 0;
    for (int num : wanted) {
      total += num;
    }

    boolean first = true;
    for (int i = 0; i < used.length && total > 0; i += 1) {
      if (!used[i]) {
        used[i] = true;
        if (!first) {
          total -= 1;
        }
        first = !first;
      }
    }

    System.out.println(findAnswer(used));
  }

  private static void buyWanted(int[] wanted, boolean[] used, ArrayList<Ticket> tickets, int day) {
    for (Ticket ticket : tickets) {
      for (int i = wanted[ticket.type]; i > 0; i -= 1) {
        int prevDay = findNotUsed(used, day);
        if (prevDay == -1) {
          break;
        }

        used[prevDay] = true;
        wanted[ticket.type] -= 1;
        day = prevDay;
      }
    }
  }

  private static int findNotUsed(boolean[] used, int startPos) {
    while (startPos >= 0) {
      if (!used[startPos]) {
        return startPos;
      }
      startPos -= 1;
    }
    return -1;
  }

  private static int findAnswer(final boolean[] used) {
    int res = 0;
    for (int i = 0; i < used.length; i += 1) {
      if (used[i]) {
        res = i;
      }
    }
    return res + 1;
  }
}

class Ticket implements Comparable<Ticket> {
  public int type;
  public int next;

  public Ticket(int type, int next) {
    this.type = type;
    this.next = next;
  }

  @Override
  public int compareTo(final Ticket other) {
    return other.next - next;
  }
}

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

public class _1165_F1 {

	public static void main(String[] args) throws Exception {
		FastScanner sc = new FastScanner(System.in);
		FastPrinter out = new FastPrinter(System.out);
		run(sc, out);
		out.close();
	}

	public static void run(FastScanner sc, FastPrinter out) throws Exception {
		int N = sc.nextInt();
		int M = sc.nextInt();
		int[][] sales = new int[M][2];
		int total = 0;
		int[] arr = new int[N];
		for (int i = 0; i < N; i++) {
			arr[i] = sc.nextInt();
			total += arr[i];
		}
		total *= 2;
		for (int i = 0; i < M; i++) {
			int a = sc.nextInt();
			int b = sc.nextInt() - 1;
			sales[i][0] = a;
			sales[i][1] = b;
		}
		Arrays.sort(sales, (a, b) -> a[0] - b[0]);
		int[] arrC = new int[N];
		int low = 0;
		int high = total;
		while (low <= high) {
			int mid = (low + high) / 2;
			for (int i = 0; i < N; i++) {
				arrC[i] = arr[i];
			}
			if (works(mid, arrC, sales, total)) {
				high = mid - 1;

			} else {
				low = mid + 1;
			}
		}
		System.out.println(low);
		// for (int day = 0;; day++) {
		// if (works(day, arrC, sales, total)) {
		// System.out.println(day);
		// return;
		// }
		// }

	}

	private static boolean works(int day, int[] arr, int[][] sales, int total) {
		int saved = 0;
		int amt = 0;
		int pDay = 0;
		for (int[] s : sales) {
			int d = s[0];
			int t = s[1];
			if (d > day) break;
			amt += d - pDay;
			pDay = d;
			int bought = Math.min(arr[t], amt);
			arr[t] -= bought;
			amt -= bought;
			saved += bought;
		}
		return day + saved >= total;
	}

	static class FastPrinter {
		static final char ENDL = '\n';
		StringBuilder buf;
		PrintWriter pw;

		public FastPrinter(OutputStream stream) {
			buf = new StringBuilder();
			pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
		}

		public FastPrinter(String fileName) throws Exception {
			buf = new StringBuilder();
			pw = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
		}

		public FastPrinter(StringBuilder buf) {
			this.buf = buf;
		}

		public void print(int a) {
			buf.append(a);
		}

		public void print(long a) {
			buf.append(a);
		}

		public void print(char a) {
			buf.append(a);
		}

		public void print(char[] a) {
			buf.append(a);
		}

		public void print(double a) {
			buf.append(a);
		}

		public void print(String a) {
			buf.append(a);
		}

		public void print(Object a) {
			buf.append(a.toString());
		}

		public void println() {
			buf.append(ENDL);
		}

		public void println(int a) {
			buf.append(a);
			buf.append(ENDL);
		}

		public void println(long a) {
			buf.append(a);
			buf.append(ENDL);
		}

		public void println(char a) {
			buf.append(a);
			buf.append(ENDL);
		}

		public void println(char[] a) {
			buf.append(a);
			buf.append(ENDL);
		}

		public void println(double a) {
			buf.append(a);
			buf.append(ENDL);
		}

		public void println(String a) {
			buf.append(a);
			buf.append(ENDL);
		}

		public void println(Object a) {
			buf.append(a.toString());
			buf.append(ENDL);
		}

		public void printf(String format, Object... args) {
			buf.append(String.format(format, args));
		}

		public void close() {
			pw.print(buf);
			pw.close();
		}

		public void flush() {
			pw.print(buf);
			pw.flush();
			buf.setLength(0);
		}

	}

	static class FastScanner {
		final private int BUFFER_SIZE = 1 << 10;
		private DataInputStream din;
		private byte[] buffer;
		private int bufferPointer, bytesRead;

		public FastScanner(InputStream stream) {
			din = new DataInputStream(stream);
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}

		public FastScanner(String fileName) throws IOException {
			Path p = Paths.get(fileName);
			buffer = Files.readAllBytes(p);
			bytesRead = buffer.length;
		}

		int[] nextIntArray(int N) throws IOException {
			int[] arr = new int[N];
			for (int i = 0; i < N; i++) {
				arr[i] = nextInt();
			}
			return arr;
		}

		String nextLine() throws IOException {
			int c = read();
			while (c != -1 && isEndline(c))
				c = read();
			if (c == -1) {
				return null;
			}
			StringBuilder res = new StringBuilder();
			do {
				if (c >= 0) {
					res.appendCodePoint(c);
				}
				c = read();
			} while (!isEndline(c));
			return res.toString();
		}

		boolean isEndline(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}

		String next() throws Exception {
			int c = readOutSpaces();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		public int nextInt() throws IOException {
			int ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg) c = read();
			do {
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');

			if (neg) return -ret;
			return ret;
		}

		public long nextLong() throws IOException {
			long ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg) c = read();
			do {
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');
			if (neg) return -ret;
			return ret;
		}

		public double nextDouble() throws IOException {
			double ret = 0, div = 1;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg) c = read();

			do {
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');

			if (c == '.') {
				while ((c = read()) >= '0' && c <= '9') {
					ret += (c - '0') / (div *= 10);
				}
			}

			if (neg) return -ret;
			return ret;
		}

		private void fillBuffer() throws IOException {
			bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
			if (bytesRead == -1) buffer[0] = -1;
		}

		private byte read() throws IOException {
			if (bufferPointer == bytesRead) fillBuffer();
			return buffer[bufferPointer++];
		}

		private int readOutSpaces() throws IOException {
			while (true) {
				if (bufferPointer == bytesRead) fillBuffer();
				int c = buffer[bufferPointer++];
				if (!isSpaceChar(c)) {
					return c;
				}
			}
		}

		public void close() throws IOException {
			if (din == null) return;
			din.close();
		}
	}

}

import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringJoiner;
import java.util.StringTokenizer;
import java.util.function.IntPredicate;

public class Main {

    static int N, M;
    static int[] K;
    static int[][] DT;

    public static void main(String[] args) {
        FastScanner sc = new FastScanner(System.in);
        N = sc.nextInt();
        M = sc.nextInt();
        K = sc.nextIntArray(N);
        DT = new int[M][2];
        for (int i = 0; i < M; i++) {
            DT[i][0] = sc.nextInt()-1;
            DT[i][1] = sc.nextInt()-1;
        }

        System.out.println(solve());
    }

    static int[] LAST;
    static int T;

    static int solve() {
        T = 0;
        for (int i = 0; i < N; i++) {
            T += K[i];
        }
        Arrays.sort(DT, Comparator.comparingInt(dt -> dt[0]));

        // 最後にセール以外で買う意味がないので調べておく
        LAST = new int[N];
        for (int i = 0; i < M; i++) {
            LAST[DT[i][1]] = DT[i][0];
        }

        return minimize(1, T*2+1, Main::calc);
    }

    // day日で終わるかどうか
    static boolean calc(int day) {
        int idx = 0;
        int money = 0;
        int bought = 0;
        for (int d = 0; d < day; d++) {
            money++;

            while( idx < M ) {
                if( DT[idx][0] < d ) {
                    idx++;

                } else if( DT[idx][0] > d ) {
                    break;

                } else {
                    int type = DT[idx][1];
                    if( d == LAST[type] ) {
                        int buy = Math.min(money, K[type]);
                        money -= buy;
                        bought += buy;
                    }
                    idx++;
                }
            }
            // debug(d, bought);
        }

        return (T - bought) * 2 <= money;
    }

    static int minimize(int lo, int hi, IntPredicate p) {
        while(lo < hi) {
            int x = ((hi - lo) >>> 1) + lo;
            if( p.test(x) ) {
                hi = x;
            } else {
                lo = x + 1;
            }
        }
        return lo;
    }

    @SuppressWarnings("unused")
    static class FastScanner {
        private BufferedReader reader;
        private StringTokenizer tokenizer;

        FastScanner(InputStream in) {
            reader = new BufferedReader(new InputStreamReader(in));
            tokenizer = null;
        }

        String next() {
            if (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        String nextLine() {
            if (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    return reader.readLine();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken("\n");
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        int[] nextIntArray(int n) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++) a[i] = nextInt();
            return a;
        }

        int[] nextIntArray(int n, int delta) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++) a[i] = nextInt() + delta;
            return a;
        }

        long[] nextLongArray(int n) {
            long[] a = new long[n];
            for (int i = 0; i < n; i++) a[i] = nextLong();
            return a;
        }
    }

    static void writeLines(int[] as) {
        PrintWriter pw = new PrintWriter(System.out);
        for (int a : as) pw.println(a);
        pw.flush();
    }

    static void writeLines(long[] as) {
        PrintWriter pw = new PrintWriter(System.out);
        for (long a : as) pw.println(a);
        pw.flush();
    }

    static void writeSingleLine(int[] as) {
        PrintWriter pw = new PrintWriter(System.out);
        for (int i = 0; i < as.length; i++) {
            if (i != 0) pw.print(" ");
            pw.print(as[i]);
        }
        pw.println();
        pw.flush();
    }

    static int max(int... as) {
        int max = Integer.MIN_VALUE;
        for (int a : as) max = Math.max(a, max);
        return max;
    }

    static int min(int... as) {
        int min = Integer.MAX_VALUE;
        for (int a : as) min = Math.min(a, min);
        return min;
    }

    static void debug(Object... args) {
        StringJoiner j = new StringJoiner(" ");
        for (Object arg : args) {
            if (arg == null) j.add("null");
            else if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg));
            else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg));
            else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg));
            else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg));
            else j.add(arg.toString());
        }
        System.err.println(j.toString());
    }

    static void printSingleLine(int[] array) {
        PrintWriter pw = new PrintWriter(System.out);
        for (int i = 0; i < array.length; i++) {
            if (i != 0) pw.print(" ");
            pw.print(array[i]);
        }
        pw.println();
        pw.flush();
    }

    static int lowerBound(int[] array, int value) {
        int lo = 0, hi = array.length, mid;
        while (lo < hi) {
            mid = (hi + lo) / 2;
            if (array[mid] < value) lo = mid + 1;
            else hi = mid;
        }
        return lo;
    }

    static int upperBound(int[] array, int value) {
        int lo = 0, hi = array.length, mid;
        while (lo < hi) {
            mid = (hi + lo) / 2;
            if (array[mid] <= value) lo = mid + 1;
            else hi = mid;
        }
        return lo;
    }
}

import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringJoiner;
import java.util.StringTokenizer;
import java.util.function.IntPredicate;

public class Main {

    static int N, M;
    static int[] K;
    static int[][] DT;

    public static void main(String[] args) {
        FastScanner sc = new FastScanner(System.in);
        N = sc.nextInt();
        M = sc.nextInt();
        K = sc.nextIntArray(N);
        DT = new int[M][2];
        for (int i = 0; i < M; i++) {
            DT[i][0] = sc.nextInt();
            DT[i][1] = sc.nextInt()-1;
        }

        System.out.println(solve());
    }

    static int[] LAST;
    static int T;
    static int[] R;

    static int solve() {
        T = 0;
        for (int i = 0; i < N; i++) {
            T += K[i];
        }
        Arrays.sort(DT, Comparator.comparingInt(dt -> dt[0]));

        // 最後にセール以外で買う意味がないので調べておく
        LAST = new int[N];
        for (int i = 0; i < M; i++) {
            LAST[DT[i][1]] = DT[i][0];
        }
        R = new int[N];

        return minimize(1, T*2+1, Main::calc);
    }

    // day日で終わるかどうか
    static boolean calc(int maxDay) {
        System.arraycopy(K, 0, R, 0, N);

        int idx = 0;
        int money = 0;
        int bought = 0;
        for (int day = 1; day <= maxDay; day++) {
            money++;

            while( idx < M ) {
                if( DT[idx][0] < day ) {
                    idx++;

                } else if( DT[idx][0] > day ) {
                    break;

                } else {
                    int type = DT[idx][1];
                    if( day == LAST[type] ) {
                        int buy = Math.min(money, R[type]);
                        money -= buy;
                        R[type] -= buy;
                        bought += buy;
                    }
                    idx++;
                }
            }
            // debug(d, bought);
        }

        return (T - bought) * 2 <= money;
    }

    static int minimize(int lo, int hi, IntPredicate p) {
        while(lo < hi) {
            int x = ((hi - lo) >>> 1) + lo;
            if( p.test(x) ) {
                hi = x;
            } else {
                lo = x + 1;
            }
        }
        return lo;
    }

    @SuppressWarnings("unused")
    static class FastScanner {
        private BufferedReader reader;
        private StringTokenizer tokenizer;

        FastScanner(InputStream in) {
            reader = new BufferedReader(new InputStreamReader(in));
            tokenizer = null;
        }

        String next() {
            if (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        String nextLine() {
            if (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    return reader.readLine();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken("\n");
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        int[] nextIntArray(int n) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++) a[i] = nextInt();
            return a;
        }

        int[] nextIntArray(int n, int delta) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++) a[i] = nextInt() + delta;
            return a;
        }

        long[] nextLongArray(int n) {
            long[] a = new long[n];
            for (int i = 0; i < n; i++) a[i] = nextLong();
            return a;
        }
    }

    static void writeLines(int[] as) {
        PrintWriter pw = new PrintWriter(System.out);
        for (int a : as) pw.println(a);
        pw.flush();
    }

    static void writeLines(long[] as) {
        PrintWriter pw = new PrintWriter(System.out);
        for (long a : as) pw.println(a);
        pw.flush();
    }

    static void writeSingleLine(int[] as) {
        PrintWriter pw = new PrintWriter(System.out);
        for (int i = 0; i < as.length; i++) {
            if (i != 0) pw.print(" ");
            pw.print(as[i]);
        }
        pw.println();
        pw.flush();
    }

    static int max(int... as) {
        int max = Integer.MIN_VALUE;
        for (int a : as) max = Math.max(a, max);
        return max;
    }

    static int min(int... as) {
        int min = Integer.MAX_VALUE;
        for (int a : as) min = Math.min(a, min);
        return min;
    }

    static void debug(Object... args) {
        StringJoiner j = new StringJoiner(" ");
        for (Object arg : args) {
            if (arg == null) j.add("null");
            else if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg));
            else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg));
            else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg));
            else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg));
            else j.add(arg.toString());
        }
        System.err.println(j.toString());
    }

    static void printSingleLine(int[] array) {
        PrintWriter pw = new PrintWriter(System.out);
        for (int i = 0; i < array.length; i++) {
            if (i != 0) pw.print(" ");
            pw.print(array[i]);
        }
        pw.println();
        pw.flush();
    }

    static int lowerBound(int[] array, int value) {
        int lo = 0, hi = array.length, mid;
        while (lo < hi) {
            mid = (hi + lo) / 2;
            if (array[mid] < value) lo = mid + 1;
            else hi = mid;
        }
        return lo;
    }

    static int upperBound(int[] array, int value) {
        int lo = 0, hi = array.length, mid;
        while (lo < hi) {
            mid = (hi + lo) / 2;
            if (array[mid] <= value) lo = mid + 1;
            else hi = mid;
        }
        return lo;
    }
}

import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringJoiner;
import java.util.StringTokenizer;
import java.util.function.IntPredicate;

public class Main {

    static int N, M;
    static int[] K;
    static int[][] DT;

    public static void main(String[] args) {
        FastScanner sc = new FastScanner(System.in);
        N = sc.nextInt();
        M = sc.nextInt();
        K = sc.nextIntArray(N);
        DT = new int[M][2];
        for (int i = 0; i < M; i++) {
            DT[i][0] = sc.nextInt()-1;
            DT[i][1] = sc.nextInt()-1;
        }

        System.out.println(solve());
    }

    static int[] LAST;
    static int T;
    static int[] R;

    static int solve() {
        T = 0;
        for (int i = 0; i < N; i++) {
            T += K[i];
        }
        Arrays.sort(DT, Comparator.comparingInt(dt -> dt[0]));

        // 最後にセール以外で買う意味がないので調べておく
        LAST = new int[N];
        for (int i = 0; i < M; i++) {
            LAST[DT[i][1]] = DT[i][0];
        }
        R = new int[N];

        return minimize(1, T*2+1, Main::calc);
    }

    // day日で終わるかどうか
    static boolean calc(int day) {
        System.arraycopy(K, 0, R, 0, N);

        int idx = 0;
        int money = 0;
        int bought = 0;
        for (int d = 0; d < day; d++) {
            money++;

            while( idx < M ) {
                if( DT[idx][0] < d ) {
                    idx++;

                } else if( DT[idx][0] > d ) {
                    break;

                } else {
                    int type = DT[idx][1];
                    if( d == LAST[type] ) {
                        int buy = Math.min(money, R[type]);
                        money -= buy;
                        R[type] -= buy;
                        bought += buy;
                    }
                    idx++;
                }
            }
            // debug(d, bought);
        }

        return (T - bought) * 2 <= money;
    }

    static int minimize(int lo, int hi, IntPredicate p) {
        while(lo < hi) {
            int x = ((hi - lo) >>> 1) + lo;
            if( p.test(x) ) {
                hi = x;
            } else {
                lo = x + 1;
            }
        }
        return lo;
    }

    @SuppressWarnings("unused")
    static class FastScanner {
        private BufferedReader reader;
        private StringTokenizer tokenizer;

        FastScanner(InputStream in) {
            reader = new BufferedReader(new InputStreamReader(in));
            tokenizer = null;
        }

        String next() {
            if (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        String nextLine() {
            if (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    return reader.readLine();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken("\n");
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        int[] nextIntArray(int n) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++) a[i] = nextInt();
            return a;
        }

        int[] nextIntArray(int n, int delta) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++) a[i] = nextInt() + delta;
            return a;
        }

        long[] nextLongArray(int n) {
            long[] a = new long[n];
            for (int i = 0; i < n; i++) a[i] = nextLong();
            return a;
        }
    }

    static void writeLines(int[] as) {
        PrintWriter pw = new PrintWriter(System.out);
        for (int a : as) pw.println(a);
        pw.flush();
    }

    static void writeLines(long[] as) {
        PrintWriter pw = new PrintWriter(System.out);
        for (long a : as) pw.println(a);
        pw.flush();
    }

    static void writeSingleLine(int[] as) {
        PrintWriter pw = new PrintWriter(System.out);
        for (int i = 0; i < as.length; i++) {
            if (i != 0) pw.print(" ");
            pw.print(as[i]);
        }
        pw.println();
        pw.flush();
    }

    static int max(int... as) {
        int max = Integer.MIN_VALUE;
        for (int a : as) max = Math.max(a, max);
        return max;
    }

    static int min(int... as) {
        int min = Integer.MAX_VALUE;
        for (int a : as) min = Math.min(a, min);
        return min;
    }

    static void debug(Object... args) {
        StringJoiner j = new StringJoiner(" ");
        for (Object arg : args) {
            if (arg == null) j.add("null");
            else if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg));
            else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg));
            else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg));
            else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg));
            else j.add(arg.toString());
        }
        System.err.println(j.toString());
    }

    static void printSingleLine(int[] array) {
        PrintWriter pw = new PrintWriter(System.out);
        for (int i = 0; i < array.length; i++) {
            if (i != 0) pw.print(" ");
            pw.print(array[i]);
        }
        pw.println();
        pw.flush();
    }

    static int lowerBound(int[] array, int value) {
        int lo = 0, hi = array.length, mid;
        while (lo < hi) {
            mid = (hi + lo) / 2;
            if (array[mid] < value) lo = mid + 1;
            else hi = mid;
        }
        return lo;
    }

    static int upperBound(int[] array, int value) {
        int lo = 0, hi = array.length, mid;
        while (lo < hi) {
            mid = (hi + lo) / 2;
            if (array[mid] <= value) lo = mid + 1;
            else hi = mid;
        }
        return lo;
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Vadim
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastScanner in = new FastScanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        r560F solver = new r560F();
        solver.solve(1, in, out);
        out.close();
    }

    static class r560F {
        private int binarySearch(Sale[] sales, int day) {
            int left = 0, right = sales.length;
            while (left < right) {
                int mid = (left + right) / 2;
                if (sales[mid].d <= day) {
                    left = mid + 1;
                } else {
                    right = mid;
                }
            }
            return left - 1;
        }

        public void solve(int testNumber, FastScanner in, PrintWriter out) {
            int N = in.ni(), M = in.ni();
            int[] k = in.na(N);
            Sale[] sales = new Sale[M];
            for (int i = 0; i < M; i++) {
                sales[i] = new Sale(in.ni(), in.ni() - 1, i);
            }
            Arrays.sort(sales, (x, y) -> {
                if (x.d == y.d)
                    return Integer.compare(x.id, y.id);
                else return Integer.compare(x.d, y.d);
            });
            int left = 0, right = 40;//todo:400_005
            int[] krem = new int[N];
            while (left < right) {
                int mid = (left + right) / 2;
                int from = binarySearch(sales, mid);
                System.arraycopy(k, 0, krem, 0, N);
                int rem = mid;
                int spent = 0;
//            System.out.println("mid = " + mid);
                for (int i = from; i >= 0 && rem > 0; --i) {
                    Sale sale = sales[i];
                    rem = Math.min(rem, sale.d);
                    if (krem[sale.t] > 0) {
                        int available = Math.min(rem, krem[sale.t]);
                        rem -= available;
                        spent += available;
                        krem[sale.t] -= available;
                    }
                }
                rem = mid - spent;
//            System.out.println("rem = " + rem);
//            System.out.println("Arrays.toString(krem) = " + Arrays.toString(krem));
                boolean correct = true;
                for (int i = 0; i < N && rem >= 0; i++) {
                    if (krem[i] > 0) {
                        rem -= krem[i] * 2;
                    }
                }
//            System.out.println("final rem = " + rem);
                if (rem < 0)
                    correct = false;

                if (!correct) {
                    left = mid + 1;
                } else {
                    right = mid;
                }
            }
            out.println(left);
        }

        class Sale {
            int d;
            int t;
            int id;

            public Sale(int d, int t, int id) {
                this.d = d;
                this.t = t;
                this.id = id;
            }

        }

    }

    static class FastScanner {
        private BufferedReader in;
        private StringTokenizer st;

        public FastScanner(InputStream stream) {
            in = new BufferedReader(new InputStreamReader(stream));
        }

        public String ns() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    String rl = in.readLine();
                    if (rl == null) {
                        return null;
                    }
                    st = new StringTokenizer(rl);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return st.nextToken();
        }

        public int ni() {
            return Integer.parseInt(ns());
        }

        public int[] na(int n) {
            int[] ret = new int[n];
            for (int i = 0; i < n; i++) {
                ret[i] = ni();
            }
            return ret;
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
        thread.start();
        thread.join();
    }

    static class TaskAdapter implements Runnable {
        @Override
        public void run() {
            InputStream inputStream = System.in;
            OutputStream outputStream = System.out;
            FastInput in = new FastInput(inputStream);
            FastOutput out = new FastOutput(outputStream);
            TaskG solver = new TaskG();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class TaskG {
        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.readInt();
            int[] a = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = in.readInt();
            }
            IntList inc = new IntList();
            IntList dec = new IntList();
            for (int i = 0; i < n; i++) {
                boolean putInc = inc.isEmpty() ||
                        a[inc.tail()] < a[i];
                boolean putDec = dec.isEmpty() ||
                        a[dec.tail()] > a[i];
                if (putInc && putDec) {
                    if (i + 1 < n && a[i] < a[i + 1]) {
                        inc.add(i);
                    } else {
                        dec.add(i);
                    }
                } else if (putInc) {
                    inc.add(i);
                } else if (putDec) {
                    dec.add(i);
                } else {
                    out.println("NO");
                    return;
                }
            }

            out.println("YES");
            inc.reverse();
            dec.reverse();
            for (int i = 0; i < n; i++) {
                if (dec.isEmpty() || (!inc.isEmpty() && inc.tail() == i)) {
                    inc.pop();
                    out.append(0).append(' ');
                } else {
                    dec.pop();
                    out.append(1).append(' ');
                }
            }
        }

    }

    static class SequenceUtils {
        public static void swap(int[] data, int i, int j) {
            int tmp = data[i];
            data[i] = data[j];
            data[j] = tmp;
        }

        public static void reverse(int[] data, int l, int r) {
            while (l < r) {
                swap(data, l, r);
                l++;
                r--;
            }
        }

        public static boolean equal(int[] a, int al, int ar, int[] b, int bl, int br) {
            if ((ar - al) != (br - bl)) {
                return false;
            }
            for (int i = al, j = bl; i <= ar; i++, j++) {
                if (a[i] != b[j]) {
                    return false;
                }
            }
            return true;
        }

    }

    static class FastInput {
        private final InputStream is;
        private byte[] buf = new byte[1 << 13];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

    }

    static class FastOutput implements AutoCloseable, Closeable {
        private StringBuilder cache = new StringBuilder(10 << 20);
        private final Writer os;

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput append(char c) {
            cache.append(c);
            return this;
        }

        public FastOutput append(int c) {
            cache.append(c);
            return this;
        }

        public FastOutput println(String c) {
            cache.append(c).append('\n');
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }

    static class IntList {
        private int size;
        private int cap;
        private int[] data;
        private static final int[] EMPTY = new int[0];

        public IntList(int cap) {
            this.cap = cap;
            if (cap == 0) {
                data = EMPTY;
            } else {
                data = new int[cap];
            }
        }

        public IntList(IntList list) {
            this.size = list.size;
            this.cap = list.cap;
            this.data = Arrays.copyOf(list.data, size);
        }

        public IntList() {
            this(0);
        }

        public void reverse(int l, int r) {
            SequenceUtils.reverse(data, l, r);
        }

        public void reverse() {
            reverse(0, size - 1);
        }

        public void ensureSpace(int req) {
            if (req > cap) {
                while (cap < req) {
                    cap = Math.max(cap + 10, 2 * cap);
                }
                data = Arrays.copyOf(data, cap);
            }
        }

        private void checkRange(int i) {
            if (i < 0 || i >= size) {
                throw new ArrayIndexOutOfBoundsException();
            }
        }

        public void add(int x) {
            ensureSpace(size + 1);
            data[size++] = x;
        }

        public int tail() {
            checkRange(0);
            return data[size - 1];
        }

        public int pop() {
            return data[--size];
        }

        public int[] toArray() {
            return Arrays.copyOf(data, size);
        }

        public boolean isEmpty() {
            return size == 0;
        }

        public String toString() {
            return Arrays.toString(toArray());
        }

        public boolean equals(Object obj) {
            if (!(obj instanceof IntList)) {
                return false;
            }
            IntList other = (IntList) obj;
            return SequenceUtils.equal(data, 0, size - 1, other.data, 0, other.size - 1);
        }

        public int hashCode() {
            int h = 1;
            for (int i = 0; i < size; i++) {
                h = h * 31 + data[i];
            }
            return h;
        }

    }
}

import java.io.*;
import java.util.*;

public class Codechef {

    static class MyScanner{
        BufferedReader br;
	StringTokenizer st;

	MyScanner(FileReader fileReader){
            br = new BufferedReader(fileReader);
	}

	MyScanner(){
            br = new BufferedReader(new InputStreamReader(System.in));
	}

	String nn(){
            while(st == null || !st.hasMoreElements()){
		try{
                    st = new StringTokenizer(br.readLine());
		}catch(IOException e){
                    e.printStackTrace();
		}
            }
            return st.nextToken();
	}

	char nc(){
            return nn().charAt(0);
	}

	int ni(){
            return Integer.parseInt(nn());
	}

	long nl(){
            return Long.parseLong(nn());
	}

	double nd(){
            return Double.parseDouble(nn());
	}

	int[] niArr0(int n){
            int[] ar = new int[n];
            for(int i = 0; i < n; i++) ar[i] = ni();
            return ar;
	}

        int[] niArr1(int n){
            int[] ar = new int[n + 1];
            for(int i = 1; i <= n; i++) ar[i] = ni();
            return ar;
	}

        long[] nlArr0(int n){
            long[] ar = new long[n];
            for(int i = 0; i < n; i++) ar[i] = nl();
            return ar;
        }

        long[] nlArr1(int n){
            long[] ar = new long[n + 1];
            for(int i = 1; i <= n; i++) ar[i] = nl();
            return ar;
        }
    }

    public static <T> void mprintln(T ... ar){
        for(T i: ar) out.print(i + " ");
        out.println();
    }

    private static PrintWriter out;

    public static void main(String[] args) throws FileNotFoundException{

        // Input from file
        // File inputFile = new File("JavaFile.txt");
        // File outputFile = new File("JavaOutputFile.txt");
        // FileReader fileReader = new FileReader(inputFile);
        // Here it ends

        MyScanner sc = new MyScanner();
        // MyScanner sc = new MyScanner(fileReader);

        out = new PrintWriter(new BufferedOutputStream(System.out)); // Output to console
        // out = new PrintWriter(new PrintStream(outputFile)); // Output to file

        getAns(sc);

        out.close();
    }

    private static void getAns(MyScanner sc){
        int n = sc.ni(), m = sc.ni();
        int[] k = sc.niArr0(n);
        HashMap<Integer, ArrayList<Integer>> map = new HashMap();

        for(int i = 0; i < m; i++){
            int day = sc.ni();
            map.putIfAbsent(day, new ArrayList<>());
            map.get(day).add(sc.ni());
        }

        int start = 1, end = 2 * (int)1e5;
        int ans = end;

//        out.println(map);

        while(start <= end){
            int mid = start + (end - start) / 2;
            if(OK(mid, map, Arrays.copyOf(k, n), n)){
                ans = mid;
                end = mid - 1;
            }else{
                start = mid + 1;
            }
        }

        out.println(ans);
    }

    private static boolean OK(int days, HashMap<Integer, ArrayList<Integer>> map, int[] k, int n){
        int cur = 0;
//        out.println(days);

        for(int i = 1; i <= days; i++){
            ++cur;
            ArrayList<Integer> index = map.get(i);
            if(index == null) continue;
            for(Integer in: index){
                int min = Math.min(cur, k[in - 1]);
                cur -= min;
                k[in - 1] -= min;
            }
        }

        for(int i = 0; i < n; i++) cur -= 2 * k[i];

        return cur >= 0;
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Washoum
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        inputClass in = new inputClass(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
        solver.solve(1, in, out);
        out.close();
    }

    static class F2MicrotransactionsHardVersion {
        static int n;
        static int m;
        static long sum;
        static int[] nb;
        static F2MicrotransactionsHardVersion.Pair[] promo;

        public void solve(int testNumber, inputClass sc, PrintWriter out) {
            n = sc.nextInt();
            m = sc.nextInt();
            nb = new int[n];
            sum = 0;
            for (int i = 0; i < n; i++) {
                nb[i] = sc.nextInt();
                sum += nb[i];
            }
            promo = new F2MicrotransactionsHardVersion.Pair[m];
            for (int i = 0; i < m; i++) {
                promo[i] = new F2MicrotransactionsHardVersion.Pair();
                promo[i].x = sc.nextInt();
                promo[i].y = sc.nextInt() - 1;
            }

            Arrays.sort(promo, new Comparator<F2MicrotransactionsHardVersion.Pair>() {

                public int compare(F2MicrotransactionsHardVersion.Pair a, F2MicrotransactionsHardVersion.Pair b) {
                    return Integer.compare(a.x, b.x);
                }
            });

            long l = 0;
            long r = (long) 1e18;
            long ans = 0;
            while (r - l >= 0) {
                long mid = (l + r) / 2;
                if (check(mid)) {
                    ans = mid;
                    r = mid - 1;
                } else {
                    l = mid + 1;
                }
            }
            out.println(ans);
        }

        static boolean check(long mid) {
            if (mid >= 2 * sum) {
                return true;
            }
            if (mid < sum) {
                return false;
            }
            int[] each = new int[n];
            System.arraycopy(nb, 0, each, 0, n);
            long kadeh = 0;
            int last = 0;
            for (int i = 0; i < m && promo[i].x <= mid; i++) {
                last = promo[i].x;
                if (i > 0) {
                    kadeh += promo[i].x - promo[i - 1].x;
                } else {
                    kadeh += promo[i].x;
                }

                if (each[promo[i].y] > 0) {
                    if (each[promo[i].y] >= kadeh) {
                        each[promo[i].y] -= kadeh;
                        kadeh = 0;
                    } else {
                        kadeh -= each[promo[i].y];
                        each[promo[i].y] = 0;
                    }
                }
            }
            kadeh += mid - last;
            long rem = 0;
            for (int i = 0; i < n; i++) {
                rem += each[i];
            }
            return kadeh >= rem * 2;
        }

        static class Pair {
            int x;
            int y;

        }

    }

    static class inputClass {
        BufferedReader br;
        StringTokenizer st;

        public inputClass(InputStream in) {

            br = new BufferedReader(new InputStreamReader(in));
        }

        public String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

import java.io.*;
import java.util.*;

public class tr0 {
	static PrintWriter out;
	static StringBuilder sb;
	static long mod =998244353;
    static int n,m,sum;
    static int[]a,ldays,ele;
    static pair []k;
	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner(System.in);
		out = new PrintWriter(System.out);
		n=sc.nextInt();
		m=sc.nextInt();
		a=new int[n];
		sum=0;
		for(int i=0;i<n;i++)
			sum+=a[i]=sc.nextInt();
	    k=new pair[m];
	    sum*=2;
	    ele=new int[n];
	    for(int i=0;i<m;i++) {
	    	int d=sc.nextInt();
	    	int x=sc.nextInt();
	    	ele[x-1]=Math.max(ele[x-1],d);
	    }
	    ldays=new int [n];
	    for(int i=0;i<n;i++) {
	    	if(ele[i]!=0) {
	    		ldays[ele[i]-1]+=a[i];
	    	}
	    }
	    int lo=0;
	    int hi=sum;
	    int ans=0;
	    while(lo<=hi) {
	    	int mid=(lo+hi)/2;
	    	if(v(mid)) {
	    		lo=mid+1;
	    		ans=mid;
	    		//out.println(mid);
	    	}
	    	else
	    		hi=mid-1;
	    }
	    out.println(ans);
		out.flush();
	}
     static boolean v(int m) {
    	 int to=0;
    	 int money=0;
    	 for(int i=0;i<m;i++) {
    		 if(i==n) {
    			 money+=m-n;
    			 break;
    		 }
    		 money++;
    		 if(ldays[i]!=0) {
    			 if(money>=ldays[i]) {
    				 money-=ldays[i];
    				 to+=ldays[i];
    			 }
    			 else if(money<ldays[i]) {
    				 to+=money;
    				 money=0;
    			 }
    		 }
    	 }
    	// if(m==8)
    		// out.println("OO"+money+" "+to);
    	 if((sum-to*2)<money)
    		 return false;
    	 return true;
     }
	static public class segmentTree {
		int[] array, tree, lazy;
		int n;

		segmentTree(int[] aa) {
			array = aa;
			n = array.length - 1;
			tree = new int[n * 4];
			lazy = new int[n * 4];
			Arrays.fill(lazy, -1);
			build(1, 1, n);
		}

		public String toString() {
			return Arrays.toString(tree);
		}

		void build(int node, int l, int r) {
			if (l == r)
				tree[node] = array[r];
			else {
				int mid = (l + r) >> 1;
				build(node << 1, l, mid);
				build((node << 1) | 1, mid + 1, r);
				tree[node] = tree[node << 1] + tree[node << 1 | 1];
			}
		}

		void updateRange(int i, int j, int v) {
			updateR(1, 1, n, i, j, v);
		}

		void updateR(int node, int l, int r, int i, int j, int v) {
			if (i > r || j < l)
				return;
			if (i <= l && j >= r) {
				tree[node] = (r - l + 1) * v;
				lazy[node] = v;
			} else {
				int mid = l + r >> 1;
				propagate(node, l, mid, r);
				updateR(node << 1, l, mid, i, j, v);
				updateR(node << 1 | 1, mid + 1, r, i, j, v);
				tree[node] = tree[node << 1] + tree[node << 1 | 1];
			}
		}

		void propagate(int node, int b, int mid, int e) {
			if (lazy[node] != -1) {
				lazy[node << 1] = lazy[node];
				lazy[node << 1 | 1] = lazy[node];
				tree[node << 1] = (mid - b + 1) * lazy[node];
				tree[node << 1 | 1] = (e - mid) * lazy[node];
			}
			lazy[node] = -1;
		}

		int query(int i, int j) {
			return query(1, 1, n, i, j);
		}

		int query(int node, int b, int e, int i, int j) // O(log n)
		{
			if (i > e || j < b)
				return 0;
			if (b >= i && e <= j)
				return tree[node];
			int mid = b + e >> 1;
			propagate(node, b, mid, e);
			int q1 = query(node << 1, b, mid, i, j);
			int q2 = query(node << 1 | 1, mid + 1, e, i, j);
			return q1 + q2;

		}

	}

	static long fac(int n) {
		if (n == 0)
			return 1;
		if (n == 1)
			return 1;
		long ans = 1;
		for (int i = 1; i <= n; i++)
			ans = (i % mod * ans % mod) % mod;
		return ans % mod;
	}

	static long gcd(long a, long b) {

		if (b == 0)
			return a;
		return gcd(b, a % b);
	}

	static class pair implements Comparable<pair> {
		int d;
		int t;

		pair(int d,int t){
			this.d=d;
			this.t=t;
		}
		public String toString() {
			return t + " " + d;
		}

		public int compareTo(pair o) {
			return o.d - d;
		}
	}

	static class unionfind {
		int[] p;
		int[] size;

		unionfind(int n) {
			p = new int[n];
			size = new int[n];

			for (int i = 0; i < n; i++) {
				p[i] = i;
			}
			Arrays.fill(size, 1);
		}

		int findSet(int v) {
			if (v == p[v])
				return v;
			return p[v] = findSet(p[v]);
		}

		boolean sameSet(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return true;
			return false;
		}

		int max() {
			int max = 0;
			for (int i = 0; i < size.length; i++)
				if (size[i] > max)
					max = size[i];
			return max;
		}

		void combine(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return;
			if (size[a] > size[b]) {
				p[b] = a;
				size[a] += size[b];

			} else {
				p[a] = b;
				size[b] += size[a];
			}
		}
	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public String nextLine() throws IOException {
			return br.readLine();
		}

		public int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		public double nextDouble() throws IOException {
			return Double.parseDouble(next());
		}

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

		public Long nextLong() throws IOException {
			return Long.parseLong(next());
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}

import java.io.*;
import java.util.*;

public class tr0 {
	static PrintWriter out;
	static StringBuilder sb;
	static long mod =998244353;
    static int n,m,sum;
    static int[]a,ldays,ele;
    static pair []k;
	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner(System.in);
		out = new PrintWriter(System.out);
		n=sc.nextInt();
		m=sc.nextInt();
		a=new int[n];
		sum=0;
		for(int i=0;i<n;i++)
			sum+=a[i]=sc.nextInt();
	    k=new pair[m];
	    sum*=2;
	    ele=new int[n];
	    for(int i=0;i<m;i++) {
	    	int d=sc.nextInt();
	    	int x=sc.nextInt();
	    	ele[x-1]=Math.max(ele[x-1],d);
	    }
	    ldays=new int [300000];
	    for(int i=0;i<n;i++) {
	    	if(ele[i]!=0) {
	    		ldays[ele[i]-1]+=a[i];
	    	}
	    }
	    int lo=0;
	    int hi=sum;
	    int ans=0;
	    while(lo<=hi) {
	    	int mid=(lo+hi)/2;
	    	//out.println(mid);
	    	if(v(mid)) {
	    		hi=mid-1;
	    		ans=mid;
	    	//	out.println(mid);
	    	}
	    	else
	    		lo=mid+1;
	    }
	    out.println(ans);
		out.flush();
	}
     static boolean v(int m) {
    	 int to=0;
    	 int money=0;
    	 for(int i=0;i<m;i++) {
    		 money++;
    		 if(ldays[i]!=0) {
    			 if(money>=ldays[i]) {
    				 money-=ldays[i];
    				 to+=ldays[i];
    			 }
    			 else if(money<ldays[i]) {
    				 to+=money;
    				 money=0;
    			 }
    		 }
    	 }
    	// if(m==214)
    		// out.println("OO "+money+" "+to+" "+sum);
    	 if((sum-to*2)>money)
    		 return false;
    	 return true;
     }
	static public class segmentTree {
		int[] array, tree, lazy;
		int n;

		segmentTree(int[] aa) {
			array = aa;
			n = array.length - 1;
			tree = new int[n * 4];
			lazy = new int[n * 4];
			Arrays.fill(lazy, -1);
			build(1, 1, n);
		}

		public String toString() {
			return Arrays.toString(tree);
		}

		void build(int node, int l, int r) {
			if (l == r)
				tree[node] = array[r];
			else {
				int mid = (l + r) >> 1;
				build(node << 1, l, mid);
				build((node << 1) | 1, mid + 1, r);
				tree[node] = tree[node << 1] + tree[node << 1 | 1];
			}
		}

		void updateRange(int i, int j, int v) {
			updateR(1, 1, n, i, j, v);
		}

		void updateR(int node, int l, int r, int i, int j, int v) {
			if (i > r || j < l)
				return;
			if (i <= l && j >= r) {
				tree[node] = (r - l + 1) * v;
				lazy[node] = v;
			} else {
				int mid = l + r >> 1;
				propagate(node, l, mid, r);
				updateR(node << 1, l, mid, i, j, v);
				updateR(node << 1 | 1, mid + 1, r, i, j, v);
				tree[node] = tree[node << 1] + tree[node << 1 | 1];
			}
		}

		void propagate(int node, int b, int mid, int e) {
			if (lazy[node] != -1) {
				lazy[node << 1] = lazy[node];
				lazy[node << 1 | 1] = lazy[node];
				tree[node << 1] = (mid - b + 1) * lazy[node];
				tree[node << 1 | 1] = (e - mid) * lazy[node];
			}
			lazy[node] = -1;
		}

		int query(int i, int j) {
			return query(1, 1, n, i, j);
		}

		int query(int node, int b, int e, int i, int j) // O(log n)
		{
			if (i > e || j < b)
				return 0;
			if (b >= i && e <= j)
				return tree[node];
			int mid = b + e >> 1;
			propagate(node, b, mid, e);
			int q1 = query(node << 1, b, mid, i, j);
			int q2 = query(node << 1 | 1, mid + 1, e, i, j);
			return q1 + q2;

		}

	}

	static long fac(int n) {
		if (n == 0)
			return 1;
		if (n == 1)
			return 1;
		long ans = 1;
		for (int i = 1; i <= n; i++)
			ans = (i % mod * ans % mod) % mod;
		return ans % mod;
	}

	static long gcd(long a, long b) {

		if (b == 0)
			return a;
		return gcd(b, a % b);
	}

	static class pair implements Comparable<pair> {
		int d;
		int t;

		pair(int d,int t){
			this.d=d;
			this.t=t;
		}
		public String toString() {
			return t + " " + d;
		}

		public int compareTo(pair o) {
			return o.d - d;
		}
	}

	static class unionfind {
		int[] p;
		int[] size;

		unionfind(int n) {
			p = new int[n];
			size = new int[n];

			for (int i = 0; i < n; i++) {
				p[i] = i;
			}
			Arrays.fill(size, 1);
		}

		int findSet(int v) {
			if (v == p[v])
				return v;
			return p[v] = findSet(p[v]);
		}

		boolean sameSet(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return true;
			return false;
		}

		int max() {
			int max = 0;
			for (int i = 0; i < size.length; i++)
				if (size[i] > max)
					max = size[i];
			return max;
		}

		void combine(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return;
			if (size[a] > size[b]) {
				p[b] = a;
				size[a] += size[b];

			} else {
				p[a] = b;
				size[b] += size[a];
			}
		}
	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public String nextLine() throws IOException {
			return br.readLine();
		}

		public int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		public double nextDouble() throws IOException {
			return Double.parseDouble(next());
		}

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

		public Long nextLong() throws IOException {
			return Long.parseLong(next());
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}

import java.io.*;
import java.util.*;

public class tr0 {
	static PrintWriter out;
	static StringBuilder sb;
	static long mod =998244353;
    static int n,m,sum;
    static int[]a,ldays,ele;
    static pair []k;
	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner(System.in);
		out = new PrintWriter(System.out);
		n=sc.nextInt();
		m=sc.nextInt();
		a=new int[n];
		sum=0;
		for(int i=0;i<n;i++)
			sum+=a[i]=sc.nextInt();
	    k=new pair[m];
	    sum*=2;
	    ele=new int[n];
	    for(int i=0;i<m;i++) {
	            k[i]=new pair(sc.nextInt(),sc.nextInt());
	    }
	    ldays=new int [500000];
	    int lo=0;
	    int hi=sum;
	    int ans=0;
	    while(lo<=hi) {
	    	int mid=(lo+hi)/2;
	//    	out.println(mid);
	    	if(v(mid)) {
	    		hi=mid-1;
	    		ans=mid;
	    	//	out.println(mid);
	    	}
	    	else
	    		lo=mid+1;
	    }
	    out.println(ans);
		out.flush();
	}
     static boolean v(int mm) {
    	 int to=0;
    	 int money=0;
    	 for(int i=0;i<m;i++) {
    		 if(k[i].d<=mm) {
 	    	ele[k[i].t-1]=Math.max(ele[k[i].t-1],k[i].d);
    		 }
 	    }
    	 ldays=new int [500000];
 	    for(int i=0;i<n;i++) {
 	    	if(ele[i]!=0) {
 	    		ldays[ele[i]-1]+=a[i];
 	    	}
 	    }
    	 for(int i=0;i<mm;i++) {
    		 money++;
    		 if(ldays[i]!=0) {
    			 if(money>=ldays[i]) {
    				 money-=ldays[i];
    				 to+=ldays[i];
    			 }
    			 else if(money<ldays[i]) {
    				 to+=money;
    				 money=0;
    			 }
    		 }
    	 }
    	// if(mm==214)
    		// out.println("OO "+money+" "+to+" "+sum);
    	 if((sum-to*2)>money)
    		 return false;
    	 return true;
     }
	static public class segmentTree {
		int[] array, tree, lazy;
		int n;

		segmentTree(int[] aa) {
			array = aa;
			n = array.length - 1;
			tree = new int[n * 4];
			lazy = new int[n * 4];
			Arrays.fill(lazy, -1);
			build(1, 1, n);
		}

		public String toString() {
			return Arrays.toString(tree);
		}

		void build(int node, int l, int r) {
			if (l == r)
				tree[node] = array[r];
			else {
				int mid = (l + r) >> 1;
				build(node << 1, l, mid);
				build((node << 1) | 1, mid + 1, r);
				tree[node] = tree[node << 1] + tree[node << 1 | 1];
			}
		}

		void updateRange(int i, int j, int v) {
			updateR(1, 1, n, i, j, v);
		}

		void updateR(int node, int l, int r, int i, int j, int v) {
			if (i > r || j < l)
				return;
			if (i <= l && j >= r) {
				tree[node] = (r - l + 1) * v;
				lazy[node] = v;
			} else {
				int mid = l + r >> 1;
				propagate(node, l, mid, r);
				updateR(node << 1, l, mid, i, j, v);
				updateR(node << 1 | 1, mid + 1, r, i, j, v);
				tree[node] = tree[node << 1] + tree[node << 1 | 1];
			}
		}

		void propagate(int node, int b, int mid, int e) {
			if (lazy[node] != -1) {
				lazy[node << 1] = lazy[node];
				lazy[node << 1 | 1] = lazy[node];
				tree[node << 1] = (mid - b + 1) * lazy[node];
				tree[node << 1 | 1] = (e - mid) * lazy[node];
			}
			lazy[node] = -1;
		}

		int query(int i, int j) {
			return query(1, 1, n, i, j);
		}

		int query(int node, int b, int e, int i, int j) // O(log n)
		{
			if (i > e || j < b)
				return 0;
			if (b >= i && e <= j)
				return tree[node];
			int mid = b + e >> 1;
			propagate(node, b, mid, e);
			int q1 = query(node << 1, b, mid, i, j);
			int q2 = query(node << 1 | 1, mid + 1, e, i, j);
			return q1 + q2;

		}

	}

	static long fac(int n) {
		if (n == 0)
			return 1;
		if (n == 1)
			return 1;
		long ans = 1;
		for (int i = 1; i <= n; i++)
			ans = (i % mod * ans % mod) % mod;
		return ans % mod;
	}

	static long gcd(long a, long b) {

		if (b == 0)
			return a;
		return gcd(b, a % b);
	}

	static class pair implements Comparable<pair> {
		int d;
		int t;

		pair(int d,int t){
			this.d=d;
			this.t=t;
		}
		public String toString() {
			return t + " " + d;
		}

		public int compareTo(pair o) {
			return o.d - d;
		}
	}

	static class unionfind {
		int[] p;
		int[] size;

		unionfind(int n) {
			p = new int[n];
			size = new int[n];

			for (int i = 0; i < n; i++) {
				p[i] = i;
			}
			Arrays.fill(size, 1);
		}

		int findSet(int v) {
			if (v == p[v])
				return v;
			return p[v] = findSet(p[v]);
		}

		boolean sameSet(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return true;
			return false;
		}

		int max() {
			int max = 0;
			for (int i = 0; i < size.length; i++)
				if (size[i] > max)
					max = size[i];
			return max;
		}

		void combine(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return;
			if (size[a] > size[b]) {
				p[b] = a;
				size[a] += size[b];

			} else {
				p[a] = b;
				size[b] += size[a];
			}
		}
	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public String nextLine() throws IOException {
			return br.readLine();
		}

		public int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		public double nextDouble() throws IOException {
			return Double.parseDouble(next());
		}

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

		public Long nextLong() throws IOException {
			return Long.parseLong(next());
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}

import java.io.*;
import java.util.*;

public class tr0 {
	static PrintWriter out;
	static StringBuilder sb;
	static long mod =998244353;
    static int n,m,sum;
    static int[]a,ldays,ele;
    static pair []k;
	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner(System.in);
		out = new PrintWriter(System.out);
		n=sc.nextInt();
		m=sc.nextInt();
		a=new int[n];
		sum=0;
		for(int i=0;i<n;i++)
			sum+=a[i]=sc.nextInt();
	    k=new pair[m];
	    sum*=2;
	    ele=new int[n];
	    for(int i=0;i<m;i++) {
	            k[i]=new pair(sc.nextInt(),sc.nextInt());
	    }
	    ldays=new int [500000];
	    for(int i=0;i<n;i++) {
	    	if(ele[i]!=0) {
	    		ldays[ele[i]-1]+=a[i];
	    	}
	    }
	    int lo=0;
	    int hi=sum;
	    int ans=0;
	    while(lo<=hi) {
	    	int mid=(lo+hi)/2;
	//    	out.println(mid);
	    	if(v(mid)) {
	    		hi=mid-1;
	    		ans=mid;
	    	//	out.println(mid);
	    	}
	    	else
	    		lo=mid+1;
	    }
	    out.println(ans);
		out.flush();
	}
     static boolean v(int mm) {
    	 int to=0;
    	 int money=0;
    	 for(int i=0;i<m;i++) {
    		 if(k[i].d<=mm) {
 	    	ele[k[i].t-1]=Math.max(ele[k[i].t-1],k[i].d);
    		 }
 	    }
    	 ldays=new int [500000];
 	    for(int i=0;i<n;i++) {
 	    	if(ele[i]!=0) {
 	    		ldays[ele[i]-1]+=a[i];
 	    	}
 	    }
    	 for(int i=0;i<mm;i++) {
    		 money++;
    		 if(ldays[i]!=0) {
    			 if(money>=ldays[i]) {
    				 money-=ldays[i];
    				 to+=ldays[i];
    			 }
    			 else if(money<ldays[i]) {
    				 to+=money;
    				 money=0;
    			 }
    		 }
    	 }
    	// if(mm==214)
    		// out.println("OO "+money+" "+to+" "+sum);
    	 if((sum-to*2)>money)
    		 return false;
    	 return true;
     }
	static public class segmentTree {
		int[] array, tree, lazy;
		int n;

		segmentTree(int[] aa) {
			array = aa;
			n = array.length - 1;
			tree = new int[n * 4];
			lazy = new int[n * 4];
			Arrays.fill(lazy, -1);
			build(1, 1, n);
		}

		public String toString() {
			return Arrays.toString(tree);
		}

		void build(int node, int l, int r) {
			if (l == r)
				tree[node] = array[r];
			else {
				int mid = (l + r) >> 1;
				build(node << 1, l, mid);
				build((node << 1) | 1, mid + 1, r);
				tree[node] = tree[node << 1] + tree[node << 1 | 1];
			}
		}

		void updateRange(int i, int j, int v) {
			updateR(1, 1, n, i, j, v);
		}

		void updateR(int node, int l, int r, int i, int j, int v) {
			if (i > r || j < l)
				return;
			if (i <= l && j >= r) {
				tree[node] = (r - l + 1) * v;
				lazy[node] = v;
			} else {
				int mid = l + r >> 1;
				propagate(node, l, mid, r);
				updateR(node << 1, l, mid, i, j, v);
				updateR(node << 1 | 1, mid + 1, r, i, j, v);
				tree[node] = tree[node << 1] + tree[node << 1 | 1];
			}
		}

		void propagate(int node, int b, int mid, int e) {
			if (lazy[node] != -1) {
				lazy[node << 1] = lazy[node];
				lazy[node << 1 | 1] = lazy[node];
				tree[node << 1] = (mid - b + 1) * lazy[node];
				tree[node << 1 | 1] = (e - mid) * lazy[node];
			}
			lazy[node] = -1;
		}

		int query(int i, int j) {
			return query(1, 1, n, i, j);
		}

		int query(int node, int b, int e, int i, int j) // O(log n)
		{
			if (i > e || j < b)
				return 0;
			if (b >= i && e <= j)
				return tree[node];
			int mid = b + e >> 1;
			propagate(node, b, mid, e);
			int q1 = query(node << 1, b, mid, i, j);
			int q2 = query(node << 1 | 1, mid + 1, e, i, j);
			return q1 + q2;

		}

	}

	static long fac(int n) {
		if (n == 0)
			return 1;
		if (n == 1)
			return 1;
		long ans = 1;
		for (int i = 1; i <= n; i++)
			ans = (i % mod * ans % mod) % mod;
		return ans % mod;
	}

	static long gcd(long a, long b) {

		if (b == 0)
			return a;
		return gcd(b, a % b);
	}

	static class pair implements Comparable<pair> {
		int d;
		int t;

		pair(int d,int t){
			this.d=d;
			this.t=t;
		}
		public String toString() {
			return t + " " + d;
		}

		public int compareTo(pair o) {
			return o.d - d;
		}
	}

	static class unionfind {
		int[] p;
		int[] size;

		unionfind(int n) {
			p = new int[n];
			size = new int[n];

			for (int i = 0; i < n; i++) {
				p[i] = i;
			}
			Arrays.fill(size, 1);
		}

		int findSet(int v) {
			if (v == p[v])
				return v;
			return p[v] = findSet(p[v]);
		}

		boolean sameSet(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return true;
			return false;
		}

		int max() {
			int max = 0;
			for (int i = 0; i < size.length; i++)
				if (size[i] > max)
					max = size[i];
			return max;
		}

		void combine(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return;
			if (size[a] > size[b]) {
				p[b] = a;
				size[a] += size[b];

			} else {
				p[a] = b;
				size[b] += size[a];
			}
		}
	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public String nextLine() throws IOException {
			return br.readLine();
		}

		public int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		public double nextDouble() throws IOException {
			return Double.parseDouble(next());
		}

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

		public Long nextLong() throws IOException {
			return Long.parseLong(next());
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main
{
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
    static class Pair implements Comparable<Pair> {
        int x,y;
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
        public int compareTo(Pair o) {
            if(x!=o.x)
                return x-o.x;
            return this.y - o.y;
        }
        public int hashCode() {
            return (int)(1L*1000000000*x + y)%1000000007;
        }
        public boolean equals(Object o) {
            if(o instanceof Pair) {
                Pair other = (Pair)o;
                return other.hashCode()==this.hashCode();
            }
            else return false;
        }
        public String toString(){
            return x+" "+y;
        }
    }
    //static Scanner sc = new Scanner(System.in);
    static Reader sc = new Reader();
    static StringBuilder sb = new StringBuilder();
    static PrintWriter pw = new PrintWriter(System.out,true);
    public static void main(String[] args) throws IOException {
        //Code start from here
        int n = sc.nextInt(),m = sc.nextInt();
        HashMap<Integer,Integer> hm = new HashMap<>();
        long total=0;
        for(int i =1;i<=n;i++){
            int val = sc.nextInt();
            hm.put(i,val);
            total+=val;
        }
        ArrayList<Pair> set = new ArrayList<>();
        for(int i =0;i<m;i++) {
            set.add(new Pair(sc.nextInt(),sc.nextInt()));
        }
        Collections.sort(set);
        int coin = set.get(m-1).x;
        for(int i =m-1;i>=0;i--) {
            Pair p = set.get(i);
            if(hm.get(p.y)>0) {
                if(hm.get(p.y)<=coin) {
                    coin-=hm.get(p.y);
                    total-=hm.get(p.y);
                } else {
                    total-=coin;
                    break;
                }
            }
           // System.out.println(coin+"  pair "+p);
        }
        long val=0;
        if(coin %2!=0)
            val=1;

        coin/=2;
        total-=coin;
        val += set.get(m-1).x + total * 2 ;
        sb.append(val);

        pw.println(sb);
        pw.flush();
        pw.close();
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Vadim
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastScanner in = new FastScanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        r560F solver = new r560F();
        solver.solve(1, in, out);
        out.close();
    }

    static class r560F {
        private int binarySearch(Sale[] sales, int day) {
            int left = 0, right = sales.length;
            while (left < right) {
                int mid = (left + right) / 2;
                if (sales[mid].d <= day) {
                    left = mid + 1;
                } else {
                    right = mid;
                }
            }
            return left - 1;
        }

        public void solve(int testNumber, FastScanner in, PrintWriter out) {
            int N = in.ni(), M = in.ni();
            int[] k = in.na(N);
            Sale[] sales = new Sale[M];
            for (int i = 0; i < M; i++) {
                sales[i] = new Sale(in.ni(), in.ni() - 1, i);
            }
            Arrays.sort(sales, (x, y) -> {
                if (x.d == y.d)
                    return Integer.compare(x.id, y.id);
                else return Integer.compare(x.d, y.d);
            });
            int left = 0, right = 40;//todo:400_005
            int[] krem = new int[N];
            while (left < right) {
                int mid = (left + right) / 2;
                int from = binarySearch(sales, mid);
                System.arraycopy(k, 0, krem, 0, N);
                int rem = mid;
                int spent = 0;
//            System.out.println("mid = " + mid);
                for (int i = from; i >= 0 && rem > 0; --i) {
                    Sale sale = sales[i];
                    rem = Math.min(rem, sale.d);
                    if (krem[sale.t] > 0) {
                        int available = Math.min(rem, krem[sale.t]);
                        rem -= available;
                        spent += available;
                        krem[sale.t] -= available;
                    }
                }
                rem = mid - spent;
//            System.out.println("rem = " + rem);
//            System.out.println("Arrays.toString(krem) = " + Arrays.toString(krem));
                boolean correct = true;
                for (int i = 0; i < N && rem > 0; i++) {
                    if (krem[i] > 0) {
                        rem -= krem[i] * 2;
                    }
                }
//            System.out.println("final rem = " + rem);
                if (rem < 0)
                    correct = false;

                if (!correct) {
                    left = mid + 1;
                } else {
                    right = mid;
                }
            }
            out.println(left);
        }

        class Sale {
            int d;
            int t;
            int id;

            public Sale(int d, int t, int id) {
                this.d = d;
                this.t = t;
                this.id = id;
            }

        }

    }

    static class FastScanner {
        private BufferedReader in;
        private StringTokenizer st;

        public FastScanner(InputStream stream) {
            in = new BufferedReader(new InputStreamReader(stream));
        }

        public String ns() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    String rl = in.readLine();
                    if (rl == null) {
                        return null;
                    }
                    st = new StringTokenizer(rl);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return st.nextToken();
        }

        public int ni() {
            return Integer.parseInt(ns());
        }

        public int[] na(int n) {
            int[] ret = new int[n];
            for (int i = 0; i < n; i++) {
                ret[i] = ni();
            }
            return ret;
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {

    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F1MikrotranzakciiUproshennayaVersiya solver = new F1MikrotranzakciiUproshennayaVersiya();
        solver.solve(1, in, out);
        out.close();
    }

    static class F1MikrotranzakciiUproshennayaVersiya {

        int[] a;
        List<Item> items;
        int sum;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            a = new int[n];
            sum = 0;
            for (int i = 0; i < n; i++) {
                a[i] = in.nextInt();
                sum += a[i];
            }

            items = new ArrayList<>();
            for (int i = 0; i < m; i++) {
                items.add(new Item(in.nextInt(), in.nextInt() - 1));
            }
            items.sort(Comparator.comparingInt(x -> x.day));

            int[] last = new int[n];
            Arrays.fill(last, -1);
            for (int i = m - 1; i >= 0; i--) {
                Item item = items.get(i);
                if (last[item.game] != -1) {
                    item.nextDay = last[item.game];
                }
                last[item.game] = item.day;
            }

            int t1 = 0;
            int t2 = (int) 1e5 + 1;
            while (t1 < t2) {
                int mid = (t1 + t2) / 2;
                if (isPossible(mid)) {
                    t2 = mid;
                } else {
                    t1 = mid + 1;
                }
            }
            out.println(t1);
        }

        private boolean isPossible(int until) {
            int idx = 0;
            int lastStop = 0;
            int money = 0;
            int taken = 0;
            while (idx < items.size() && items.get(idx).day <= until) {
                Item item = items.get(idx);
                if (item.nextDay <= until) {
                    idx++;
                    continue;
                }
                money += item.day - lastStop;
                lastStop = item.day;
                int toTake = Math.min(money, a[item.game]);
                taken += toTake;
                money -= toTake;
                idx++;
            }
            money += until - lastStop;
            return (sum - taken) * 2 <= money;
        }

        class Item {

            int day;
            int game;
            int nextDay = (int) 1e6;

            public Item(int day, int game) {
                this.day = day;
                this.game = game;
            }
        }
    }

    static class InputReader {

        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {

    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F1MikrotranzakciiUproshennayaVersiya solver = new F1MikrotranzakciiUproshennayaVersiya();
        solver.solve(1, in, out);
        out.close();
    }

    static class F1MikrotranzakciiUproshennayaVersiya {

        int[] a;
        List<Item> items;
        int sum;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            a = new int[n];
            sum = 0;
            for (int i = 0; i < n; i++) {
                a[i] = in.nextInt();
                sum += a[i];
            }

            items = new ArrayList<>();
            for (int i = 0; i < m; i++) {
                items.add(new Item(in.nextInt(), in.nextInt() - 1));
            }
            items.sort(Comparator.comparingInt(x -> x.day));

            int[] last = new int[n];
            Arrays.fill(last, -1);
            for (int i = m - 1; i >= 0; i--) {
                Item item = items.get(i);
                if (last[item.game] != -1) {
                    item.nextDay = last[item.game];
                }
                last[item.game] = item.day;
            }

            int t1 = 0;
            int t2 = (int) 2e5 + 1;
            while (t1 < t2) {
                int mid = (t1 + t2) / 2;
                if (isPossible(mid)) {
                    t2 = mid;
                } else {
                    t1 = mid + 1;
                }
            }
            out.println(t1);
        }

        private boolean isPossible(int until) {
            int idx = 0;
            int lastStop = 0;
            int money = 0;
            int taken = 0;
            while (idx < items.size() && items.get(idx).day <= until) {
                Item item = items.get(idx);
                if (item.nextDay <= until) {
                    idx++;
                    continue;
                }
                money += item.day - lastStop;
                lastStop = item.day;
                int toTake = Math.min(money, a[item.game]);
                taken += toTake;
                money -= toTake;
                idx++;
            }
            money += until - lastStop;
            return (sum - taken) * 2 <= money;
        }

        class Item {

            int day;
            int game;
            int nextDay = (int) 1e6;

            public Item(int day, int game) {
                this.day = day;
                this.game = game;
            }
        }
    }

    static class InputReader {

        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }
    }
}

import java.util.*;
import java.io.*;
import static java.lang.Math.*;
import java.math.BigInteger;
public class Main {
    static final long MOD = 998244353, INF = 1_000_000_000_000_000L;
    static final int INf = 1_000_000_000;
    static FastReader reader;
    static PrintWriter writer;
    public static void main(String[] args) {
        Thread t = new Thread(null, new O(), "Integer.MAX_VALUE", 100000000);
        t.start();
    }
    static class O implements Runnable {
        public void run() {
            try {
                magic();
            }
            catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
    }
    static class FastReader {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public FastReader() {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public FastReader(String file_name) throws IOException {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException {
            byte[] buf = new byte[1000000];
            int cnt = 0, c;
            while ((c = read()) != -1) {
                if (c == '\n') break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException {
            int ret = 0;
            byte c = read();
            while (c <= ' ') c = read();
            boolean neg = (c == '-');
            if (neg) c = read();
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (neg) return -ret;
            return ret;
        }

        public long nextLong() throws IOException {
            long ret = 0;
            byte c = read();
            while (c <= ' ') c = read();
            boolean neg = (c == '-');
            if (neg) c = read();
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (neg) return -ret;
            return ret;
        }

        public double nextDouble() throws IOException {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ') c = read();
            boolean neg = (c == '-');
            if (neg) c = read();
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10);
            if (neg) return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1) buffer[0] = -1;
        }

        private byte read() throws IOException {
            if (bufferPointer == bytesRead) fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException {
            if (din == null) return;
            din.close();
        }
    }
    static int n,m,k[],rem[];
    static Pair offers[];
    static void magic() throws IOException {
        reader = new FastReader();
        writer = new PrintWriter(System.out, true);
        n = reader.nextInt();
        m = reader.nextInt();
        k = new int[n];
        rem = new int[n];
        for(int i=0;i<n;++i) {
            k[i] = reader.nextInt();
        }
        offers = new Pair[m];
        for(int i=0;i<m;++i) {
            offers[i] = new Pair(reader.nextInt(), reader.nextInt()-1);
        }
        Arrays.sort(offers);
        int low = 1, high = 4000000, mid;
        while(low<high) {
            mid = (low+high)>>1;
            if(check(mid)) {
                if(!check(mid-1)) {
                    low = mid;
                    break;
                }
                else high = --mid;
            }
            else low = ++mid;
        }
        writer.println(low);
    }
    static boolean check(int D) {
        for(int i=0;i<n;++i) {
            rem[i] = k[i];
        }
        int curr = 0, prev = 0;
        for(int i=0;i<m;++i) {
            if(offers[i].x>D) {
                break;
            }
            curr+=offers[i].x - prev;
            int kharida = min(curr, rem[offers[i].y]);
            rem[offers[i].y]-=kharida;
            curr-=kharida;
            prev = offers[i].x;
        }
        curr+=(D-prev);
        int left = 0;
        for(int i=0;i<n;++i) {
            left+=rem[i];
        }
        return curr>=2*left;
    }
    static class Pair implements Comparable<Pair>
    {
        int x,y;
        Pair(int x,int y)
        {
            this.x=x;
            this.y=y;
        }
        public int compareTo(Pair other)
        {
            if(this.x!=other.x)
                return this.x-other.x;
            return this.y-other.y;
        }
        public String toString()
        {
            return "("+x+","+y+")";
        }
    }
}

import java.util.*;
import java.io.*;
import static java.lang.Math.*;
import java.math.BigInteger;
public class Main {
    static final long MOD = 998244353, INF = 1_000_000_000_000_000L;
    static final int INf = 1_000_000_000;
    static FastReader reader;
    static PrintWriter writer;
    public static void main(String[] args) {
        Thread t = new Thread(null, new O(), "Integer.MAX_VALUE", 100000000);
        t.start();
    }
    static class O implements Runnable {
        public void run() {
            try {
                magic();
            }
            catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
    }
    static class FastReader {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public FastReader() {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public FastReader(String file_name) throws IOException {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException {
            byte[] buf = new byte[1000000];
            int cnt = 0, c;
            while ((c = read()) != -1) {
                if (c == '\n') break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException {
            int ret = 0;
            byte c = read();
            while (c <= ' ') c = read();
            boolean neg = (c == '-');
            if (neg) c = read();
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (neg) return -ret;
            return ret;
        }

        public long nextLong() throws IOException {
            long ret = 0;
            byte c = read();
            while (c <= ' ') c = read();
            boolean neg = (c == '-');
            if (neg) c = read();
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (neg) return -ret;
            return ret;
        }

        public double nextDouble() throws IOException {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ') c = read();
            boolean neg = (c == '-');
            if (neg) c = read();
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10);
            if (neg) return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1) buffer[0] = -1;
        }

        private byte read() throws IOException {
            if (bufferPointer == bytesRead) fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException {
            if (din == null) return;
            din.close();
        }
    }
    static int n,m,k[],rem[];
    static Pair offers[];
    static void magic() throws IOException {
        reader = new FastReader();
        writer = new PrintWriter(System.out, true);
        n = reader.nextInt();
        m = reader.nextInt();
        k = new int[n];
        rem = new int[n];
        for(int i=0;i<n;++i) {
            k[i] = reader.nextInt();
        }
        offers = new Pair[m];
        for(int i=0;i<m;++i) {
            offers[i] = new Pair(reader.nextInt(), reader.nextInt());
        }
        Arrays.sort(offers);
        int low = 0, high = 4000000, mid;
        while(low<high) {
            mid = (low+high)>>1;
            if(check(mid)) {
                if(!check(mid-1)) {
                    low = mid;
                    break;
                }
                else high = --mid;
            }
            else low = ++mid;
        }
        writer.println(low);
    }
    static boolean check(int D) {
        for(int i=0;i<n;++i) {
            rem[i] = k[i];
        }
        int curr = 0, prev = 0;
        for(int i=0;i<m;++i) {
            if(offers[i].x>D) {
                break;
            }
            curr+=offers[i].x - prev;
            int kharida = min(curr, rem[offers[i].y-1]);
            rem[offers[i].y-1]-=kharida;
            curr-=kharida;
            prev = offers[i].x;
        }
        curr+=(D-prev);
        int left = 0;
        for(int i=0;i<n;++i) {
            left+=rem[i];
        }
        return curr>=2*left;
    }
    static class Pair implements Comparable<Pair>
    {
        int x,y;
        Pair(int x,int y)
        {
            this.x=x;
            this.y=y;
        }
        public int compareTo(Pair other)
        {
            if(this.x!=other.x)
                return this.x-other.x;
            return this.y-other.y;
        }
        public String toString()
        {
            return "("+x+","+y+")";
        }
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
    static int inf = (int) 1e9 + 7;

    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        pw = new PrintWriter(System.out);
        int n = nextInt();
        int m = nextInt();
        long a[] = new long [n];
        sale b[] = new sale[m];
        for(int i = 0;i < n;i++) a[i] = nextInt();
        for(int i = 0;i < m;i++) b[i] = new sale(nextInt(), nextInt() - 1);
        Arrays.sort(b, new sale());
        long l = 0;
        long r = 100000000000l;
        long a_[] = new long [n];
        for(int i = 0;i < n;i++) a_[i] = a[i];
        if (b[0].d > 390000) n /= 0;
        while(l != r - 1) {
            long mid = (l + r) / 2;
            long cnt1 = mid;
            long cnt2 = 0;
            int id = m - 1;
            while(b[id].d >= mid) {
                id--;
            }
            while(id >= 0) {
                if (cnt1 > b[id].d) {
                    cnt2 += cnt1 - b[id].d;
                    cnt1 = b[id].d;
                }
                long u = Math.min(a[b[id].t], cnt1);
                a[b[id].t] -= u;
                cnt1 -= u;
                id--;
            }
            boolean can = true;
            for(int i = 0;i < n;i++) {
                if (a[i] * 2 > cnt2) can = false;
                cnt2 -= a[i] * 2;
                a[i] = 0;
            }
            for(int i = 0;i < n;i++) a[i] = a_[i];
            if (can) r = mid;
            else l = mid;
        }
        pw.print(r);
        pw.close();
    }

    static BufferedReader br;
    static StringTokenizer st = new StringTokenizer("");
    static PrintWriter pw;

    static String next() throws IOException {
        while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static long nextLong() throws IOException {
        return Long.parseLong(next());
    }
}
class sale implements Comparator<sale>{
    long d; int t;
    sale(long d, int t) {
        this.d = d;
        this.t = t;
    }
    sale() {}

    @Override
    public int compare(sale o1, sale o2) {
        return Long.compare(o1.d, o2.d);
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
    static int inf = (int) 1e9 + 7;

    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        pw = new PrintWriter(System.out);
        int n = nextInt();
        int m = nextInt();
        long a[] = new long [n];
        sale b[] = new sale[m];
        for(int i = 0;i < n;i++) a[i] = nextInt();
        for(int i = 0;i < m;i++) b[i] = new sale(nextInt() - 1, nextInt() - 1);
        Arrays.sort(b, new sale());
        long l = 0;
        long r = 100000000000l;
        long a_[] = new long [n];
        for(int i = 0;i < n;i++) a_[i] = a[i];
        while(l != r - 1) {
            long mid = (l + r) / 2;
            long cnt1 = mid;
            long cnt2 = 0;
            int id = m - 1;
            while(b[id].d > mid) {
                id--;
            }
            while(id >= 0) {
                if (cnt1 > b[id].d) {
                    cnt2 += cnt1 - b[id].d;
                    cnt1 = b[id].d;
                }
                long u = Math.min(a[b[id].t], cnt1);
                a[b[id].t] -= u;
                cnt1 -= u;
                id--;
            }
            boolean can = true;
            for(int i = 0;i < n;i++) {
                if (a[i] * 2 > cnt2) can = false;
                cnt2 -= a[i] * 2;
                a[i] = 0;
            }
            for(int i = 0;i < n;i++) a[i] = a_[i];
            if (can) r = mid;
            else l = mid;
        }
        pw.print(r);
        pw.close();
    }

    static BufferedReader br;
    static StringTokenizer st = new StringTokenizer("");
    static PrintWriter pw;

    static String next() throws IOException {
        while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static long nextLong() throws IOException {
        return Long.parseLong(next());
    }
}
class sale implements Comparator<sale>{
    long d; int t;
    sale(long d, int t) {
        this.d = d;
        this.t = t;
    }
    sale() {}

    @Override
    public int compare(sale o1, sale o2) {
        return Long.compare(o1.d, o2.d);
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
    static int inf = (int) 1e9 + 7;

    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        pw = new PrintWriter(System.out);
        int n = nextInt();
        int m = nextInt();
        long a[] = new long [n];
        sale b[] = new sale[m];
        for(int i = 0;i < n;i++) a[i] = nextInt();
        for(int i = 0;i < m;i++) b[i] = new sale(nextInt(), nextInt() - 1);
        Arrays.sort(b, new sale());
        long l = 0;
        long r = 100000000000l;
        long a_[] = new long [n];
        for(int i = 0;i < n;i++) a_[i] = a[i];
        while(l != r - 1) {
            long mid = (l + r) / 2;
            long cnt1 = mid;
            long cnt2 = 0;
            int id = m - 1;
            while(b[id].d >= mid) {
                id--;
            }
            while(id >= 0) {
                if (cnt1 >= b[id].d) {
                    cnt2 += cnt1 - b[id].d;
                    cnt1 = b[id].d - 1;
                }
                long u = Math.min(a[b[id].t], cnt1);
                a[b[id].t] -= u;
                cnt1 -= u;
                id--;
            }
            boolean can = true;
            for(int i = 0;i < n;i++) {
                if (a[i] * 2 > cnt2) can = false;
                cnt2 -= a[i] * 2;
                a[i] = 0;
            }
            for(int i = 0;i < n;i++) a[i] = a_[i];
            if (can) r = mid;
            else l = mid;
        }
        pw.print(r);
        pw.close();
    }

    static BufferedReader br;
    static StringTokenizer st = new StringTokenizer("");
    static PrintWriter pw;

    static String next() throws IOException {
        while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static long nextLong() throws IOException {
        return Long.parseLong(next());
    }
}
class sale implements Comparator<sale>{
    long d; int t;
    sale(long d, int t) {
        this.d = d;
        this.t = t;
    }
    sale() {}

    @Override
    public int compare(sale o1, sale o2) {
        return Long.compare(o1.d, o2.d);
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
    static int inf = (int) 1e9 + 7;

    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        pw = new PrintWriter(System.out);
        int n = nextInt();
        int m = nextInt();
        long a[] = new long [n];
        sale b[] = new sale[m];
        for(int i = 0;i < n;i++) a[i] = nextInt();
        for(int i = 0;i < m;i++) b[i] = new sale(nextInt(), nextInt() - 1);
        Arrays.sort(b, new sale());
        long l = 0;
        long r = 100000000000l;
        long a_[] = new long [n];
        for(int i = 0;i < n;i++) a_[i] = a[i];
        while(l != r - 1) {
            long mid = (l + r) / 2;
            long cnt1 = mid;
            long cnt2 = 0;
            int id = m - 1;
            while(b[id].d >= mid) {
                id--;
            }
            while(id >= 0) {
                if (cnt1 >= b[id].d) {
                    cnt2 += cnt1 - b[id].d;
                    cnt1 = b[id].d;
                }
                long u = Math.min(a[b[id].t], cnt1);
                a[b[id].t] -= u;
                cnt1 -= u;
                id--;
            }
            boolean can = true;
            for(int i = 0;i < n;i++) {
                if (a[i] * 2 > cnt2) can = false;
                cnt2 -= a[i] * 2;
                a[i] = 0;
            }
            for(int i = 0;i < n;i++) a[i] = a_[i];
            if (can) r = mid;
            else l = mid;
        }
        pw.print(r);
        pw.close();
    }

    static BufferedReader br;
    static StringTokenizer st = new StringTokenizer("");
    static PrintWriter pw;

    static String next() throws IOException {
        while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static long nextLong() throws IOException {
        return Long.parseLong(next());
    }
}
class sale implements Comparator<sale>{
    long d; int t;
    sale(long d, int t) {
        this.d = d;
        this.t = t;
    }
    sale() {}

    @Override
    public int compare(sale o1, sale o2) {
        return Long.compare(o1.d, o2.d);
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
    static int inf = (int) 1e9 + 7;

    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        pw = new PrintWriter(System.out);
        int n = nextInt();
        int m = nextInt();
        int a[] = new int [n];
        sale b[] = new sale[m];
        for(int i = 0;i < n;i++) a[i] = nextInt();
        for(int i = 0;i < m;i++) b[i] = new sale(nextInt(), nextInt() - 1);
        Arrays.sort(b, new sale());
        long l = 0;
        long r = 100000000000l;
        int a_[] = new int [n];
        for(int i = 0;i < n;i++) a_[i] = a[i];
        while(l != r - 1) {
            long mid = (l + r) / 2;
            long cnt1 = mid;
            long cnt2 = 0;
            int id = m - 1;
            while(b[id].d > mid) {
                id--;
            }
            while(id >= 0) {
                if (cnt1 > b[id].d) {
                    cnt2 += cnt1 - b[id].d;
                    cnt1 = b[id].d;
                }
                long u = Math.min(a[b[id].t], cnt1);
                a[b[id].t] -= u;
                cnt1 -= u;
                id--;
            }
            boolean can = true;
            for(int i = 0;i < n;i++) {
                if (a[i] * 2 > cnt2) can = false;
                cnt2 -= a[i] * 2;
                a[i] = 0;
            }
            for(int i = 0;i < n;i++) a[i] = a_[i];
            if (can) r = mid;
            else l = mid;
        }
        pw.print(r);
        pw.close();
    }

    static BufferedReader br;
    static StringTokenizer st = new StringTokenizer("");
    static PrintWriter pw;

    static String next() throws IOException {
        while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static long nextLong() throws IOException {
        return Long.parseLong(next());
    }
}
class sale implements Comparator<sale>{
    int d, t;
    sale(int d, int t) {
        this.d = d;
        this.t = t;
    }
    sale() {}

    @Override
    public int compare(sale o1, sale o2) {
        return Integer.compare(o1.d, o2.d);
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
    static int inf = (int) 1e9 + 7;

    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        pw = new PrintWriter(System.out);
        int n = nextInt();
        int m = nextInt();
        long a[] = new long [n];
        sale b[] = new sale[m];
        for(int i = 0;i < n;i++) a[i] = nextInt();
        for(int i = 0;i < m;i++) b[i] = new sale(nextInt(), nextInt() - 1);
        Arrays.sort(b, new sale());
        long l = 0;
        long r = 100000000000l;
        long a_[] = new long [n];
        for(int i = 0;i < n;i++) a_[i] = a[i];
        while(l != r - 1) {
            long mid = (l + r) / 2;
            long cnt1 = mid;
            long cnt2 = 0;
            int id = m - 1;
            while(b[id].d >= mid) {
                id--;
            }
            while(id >= 0) {
                if (cnt1 > b[id].d) {
                    cnt2 += cnt1 - b[id].d;
                    cnt1 = b[id].d;
                }
                long u = Math.min(a[b[id].t], cnt1);
                a[b[id].t] -= u;
                cnt1 -= u;
                id--;
            }
            boolean can = true;
            for(int i = 0;i < n;i++) {
                if (a[i] * 2 > cnt2) can = false;
                cnt2 -= a[i] * 2;
                a[i] = 0;
            }
            for(int i = 0;i < n;i++) a[i] = a_[i];
            if (can) r = mid;
            else l = mid;
        }
        pw.print(r);
        pw.close();
    }

    static BufferedReader br;
    static StringTokenizer st = new StringTokenizer("");
    static PrintWriter pw;

    static String next() throws IOException {
        while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static long nextLong() throws IOException {
        return Long.parseLong(next());
    }
}
class sale implements Comparator<sale>{
    long d; int t;
    sale(long d, int t) {
        this.d = d;
        this.t = t;
    }
    sale() {}

    @Override
    public int compare(sale o1, sale o2) {
        return Long.compare(o1.d, o2.d);
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
    static int inf = (int) 1e9 + 7;

    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        pw = new PrintWriter(System.out);
        int n = nextInt();
        int m = nextInt();
        long a[] = new long [n];
        sale b[] = new sale[m];
        for(int i = 0;i < n;i++) a[i] = nextInt();
        for(int i = 0;i < m;i++) b[i] = new sale(nextInt(), nextInt() - 1);
        Arrays.sort(b, new sale());
        long l = 0;
        long r = 100000000000l;
        long a_[] = new long [n];
        for(int i = 0;i < n;i++) a_[i] = a[i];
        if (b[0].d == 400000) n /= 0;
        while(l != r - 1) {
            long mid = (l + r) / 2;
            long cnt1 = mid;
            long cnt2 = 0;
            int id = m - 1;
            while(b[id].d >= mid) {
                id--;
            }
            while(id >= 0) {
                if (cnt1 > b[id].d) {
                    cnt2 += cnt1 - b[id].d;
                    cnt1 = b[id].d;
                }
                long u = Math.min(a[b[id].t], cnt1);
                a[b[id].t] -= u;
                cnt1 -= u;
                id--;
            }
            boolean can = true;
            for(int i = 0;i < n;i++) {
                if (a[i] * 2 > cnt2) can = false;
                cnt2 -= a[i] * 2;
                a[i] = 0;
            }
            for(int i = 0;i < n;i++) a[i] = a_[i];
            if (can) r = mid;
            else l = mid;
        }
        pw.print(r);
        pw.close();
    }

    static BufferedReader br;
    static StringTokenizer st = new StringTokenizer("");
    static PrintWriter pw;

    static String next() throws IOException {
        while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static long nextLong() throws IOException {
        return Long.parseLong(next());
    }
}
class sale implements Comparator<sale>{
    long d; int t;
    sale(long d, int t) {
        this.d = d;
        this.t = t;
    }
    sale() {}

    @Override
    public int compare(sale o1, sale o2) {
        return Long.compare(o1.d, o2.d);
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
        thread.start();
        thread.join();
    }

    static class TaskAdapter implements Runnable {
        @Override
        public void run() {
            InputStream inputStream = System.in;
            OutputStream outputStream = System.out;
            FastInput in = new FastInput(inputStream);
            FastOutput out = new FastOutput(outputStream);
            F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class F2MicrotransactionsHardVersion {
        long inf = (long) 1e18;

        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.readInt();
            int m = in.readInt();
            int[] k = new int[n];
            int[] remains = new int[n];
            for (int i = 0; i < n; i++) {
                k[i] = in.readInt();
            }

            Discount[] discounts = new Discount[m];
            for (int j = 0; j < m; j++) {
                discounts[j] = new Discount();
                discounts[j].d = in.readInt();
                discounts[j].t = in.readInt() - 1;
            }

            Arrays.sort(discounts, (a, b) -> a.d - b.d);
            long[] lastDay = new long[n];
            Arrays.fill(lastDay, inf);
            for (int i = 0; i < m; i++) {
                discounts[i].nextDay = lastDay[discounts[i].t];
                lastDay[discounts[i].t] = discounts[i].nextDay;
            }

            LongBinarySearch bs = new LongBinarySearch() {

                public boolean check(long mid) {
                    long used = 0;
                    System.arraycopy(k, 0, remains, 0, n);
                    for (int i = 0; i < m && discounts[i].d <= mid; i++) {
                        if (discounts[i].nextDay <= mid) {
                            continue;
                        }
                        int consume = (int) Math.min(discounts[i].d - used, remains[discounts[i].t]);
                        used += consume;
                        remains[discounts[i].t] -= consume;
                    }
                    for (int i = 0; i < n; i++) {
                        used += 2 * remains[i];
                    }
                    return used <= mid;
                }
            };

            long ans = bs.binarySearch(0, (long) 1e11);
            out.println(ans);
        }

    }

    static class Discount {
        int d;
        int t;
        long nextDay;

    }

    static class FastInput {
        private final InputStream is;
        private byte[] buf = new byte[1 << 13];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

    }

    static class FastOutput implements AutoCloseable, Closeable {
        private StringBuilder cache = new StringBuilder(10 << 20);
        private final Writer os;

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput println(long c) {
            cache.append(c).append('\n');
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }

    static abstract class LongBinarySearch {
        public abstract boolean check(long mid);

        public long binarySearch(long l, long r) {
            if (l > r) {
                throw new IllegalArgumentException();
            }
            while (l < r) {
                long mid = (l + r) >>> 1;
                if (check(mid)) {
                    r = mid;
                } else {
                    l = mid + 1;
                }
            }
            return l;
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
        thread.start();
        thread.join();
    }

    static class TaskAdapter implements Runnable {
        @Override
        public void run() {
            InputStream inputStream = System.in;
            OutputStream outputStream = System.out;
            FastInput in = new FastInput(inputStream);
            FastOutput out = new FastOutput(outputStream);
            F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class F2MicrotransactionsHardVersion {
        long inf = (long) 1e18;

        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.readInt();
            int m = in.readInt();
            int[] k = new int[n];
            int[] remains = new int[n];
            for (int i = 0; i < n; i++) {
                k[i] = in.readInt();
            }

            Discount[] discounts = new Discount[m];
            for (int j = 0; j < m; j++) {
                discounts[j] = new Discount();
                discounts[j].d = in.readInt();
                discounts[j].t = in.readInt() - 1;
            }

            Arrays.sort(discounts, (a, b) -> a.d - b.d);
            long[] lastDay = new long[n];
            Arrays.fill(lastDay, inf);
            for (int i = 0; i < m; i++) {
                discounts[i].nextDay = lastDay[discounts[i].t];
                lastDay[discounts[i].t] = discounts[i].d;
            }

            LongBinarySearch bs = new LongBinarySearch() {

                public boolean check(long mid) {
                    long used = 0;
                    System.arraycopy(k, 0, remains, 0, n);
                    for (int i = 0; i < m && discounts[i].d <= mid; i++) {
                        if (discounts[i].nextDay <= mid) {
                            continue;
                        }
                        int consume = (int) Math.min(discounts[i].d - used, remains[discounts[i].t]);
                        used += consume;
                        remains[discounts[i].t] -= consume;
                    }
                    for (int i = 0; i < n; i++) {
                        used += 2 * remains[i];
                    }
                    return used <= mid;
                }
            };

            long ans = bs.binarySearch(0, (long) 1e11);
            out.println(ans);
        }

    }

    static class Discount {
        int d;
        int t;
        long nextDay;

    }

    static class FastInput {
        private final InputStream is;
        private byte[] buf = new byte[1 << 13];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

    }

    static class FastOutput implements AutoCloseable, Closeable {
        private StringBuilder cache = new StringBuilder(10 << 20);
        private final Writer os;

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput println(long c) {
            cache.append(c).append('\n');
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }

    static abstract class LongBinarySearch {
        public abstract boolean check(long mid);

        public long binarySearch(long l, long r) {
            if (l > r) {
                throw new IllegalArgumentException();
            }
            while (l < r) {
                long mid = (l + r) >>> 1;
                if (check(mid)) {
                    r = mid;
                } else {
                    l = mid + 1;
                }
            }
            return l;
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
        thread.start();
        thread.join();
    }

    static class TaskAdapter implements Runnable {
        @Override
        public void run() {
            InputStream inputStream = System.in;
            OutputStream outputStream = System.out;
            FastInput in = new FastInput(inputStream);
            FastOutput out = new FastOutput(outputStream);
            F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class F2MicrotransactionsHardVersion {
        long inf = (long) 1e18;

        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.readInt();
            int m = in.readInt();
            int[] k = new int[n];
            int[] remains = new int[n];
            for (int i = 0; i < n; i++) {
                k[i] = in.readInt();
            }

            Discount[] discounts = new Discount[m];
            for (int j = 0; j < m; j++) {
                discounts[j] = new Discount();
                discounts[j].d = in.readInt();
                discounts[j].t = in.readInt() - 1;
            }

            Arrays.sort(discounts, (a, b) -> a.d - b.d);
            long[] lastDay = new long[n];
            Arrays.fill(lastDay, inf);
            for (int i = 0; i < m; i++) {
                discounts[i].nextDay = lastDay[discounts[i].t];
                lastDay[discounts[i].t] = discounts[i].nextDay;
            }

            LongBinarySearch bs = new LongBinarySearch() {

                public boolean check(long mid) {
                    long used = 0;
                    System.arraycopy(k, 0, remains, 0, n);
                    for (int i = 0; i < m; i++) {
                        if (discounts[i].nextDay <= mid) {
                            continue;
                        }
                        int consume = (int) Math.min(discounts[i].d - used, remains[discounts[i].t]);
                        used += consume;
                        remains[discounts[i].t] -= consume;
                    }
                    for (int i = 0; i < n; i++) {
                        used += 2 * remains[i];
                    }
                    return used <= mid;
                }
            };

            long ans = bs.binarySearch(0, (long) 1e11);
            out.println(ans);
        }

    }

    static class Discount {
        int d;
        int t;
        long nextDay;

    }

    static class FastInput {
        private final InputStream is;
        private byte[] buf = new byte[1 << 13];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

    }

    static class FastOutput implements AutoCloseable, Closeable {
        private StringBuilder cache = new StringBuilder(10 << 20);
        private final Writer os;

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput println(long c) {
            cache.append(c).append('\n');
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }

    static abstract class LongBinarySearch {
        public abstract boolean check(long mid);

        public long binarySearch(long l, long r) {
            if (l > r) {
                throw new IllegalArgumentException();
            }
            while (l < r) {
                long mid = (l + r) >>> 1;
                if (check(mid)) {
                    r = mid;
                } else {
                    l = mid + 1;
                }
            }
            return l;
        }

    }
}

import java.io.*;
import java.util.*;

public class Codechef {

    static class MyScanner{
        BufferedReader br;
	StringTokenizer st;

	MyScanner(FileReader fileReader){
            br = new BufferedReader(fileReader);
	}

	MyScanner(){
            br = new BufferedReader(new InputStreamReader(System.in));
	}

	String nn(){
            while(st == null || !st.hasMoreElements()){
		try{
                    st = new StringTokenizer(br.readLine());
		}catch(IOException e){
                    e.printStackTrace();
		}
            }
            return st.nextToken();
	}

	char nc(){
            return nn().charAt(0);
	}

	int ni(){
            return Integer.parseInt(nn());
	}

	long nl(){
            return Long.parseLong(nn());
	}

	double nd(){
            return Double.parseDouble(nn());
	}

	int[] niArr0(int n){
            int[] ar = new int[n];
            for(int i = 0; i < n; i++) ar[i] = ni();
            return ar;
	}

        int[] niArr1(int n){
            int[] ar = new int[n + 1];
            for(int i = 1; i <= n; i++) ar[i] = ni();
            return ar;
	}

        long[] nlArr0(int n){
            long[] ar = new long[n];
            for(int i = 0; i < n; i++) ar[i] = nl();
            return ar;
        }

        long[] nlArr1(int n){
            long[] ar = new long[n + 1];
            for(int i = 1; i <= n; i++) ar[i] = nl();
            return ar;
        }
    }

    public static <T> void mprintln(T ... ar){
        for(T i: ar) out.print(i + " ");
        out.println();
    }

    private static PrintWriter out;

    public static void main(String[] args) throws FileNotFoundException{

        // Input from file
        // File inputFile = new File("JavaFile.txt");
        // File outputFile = new File("JavaOutputFile.txt");
        // FileReader fileReader = new FileReader(inputFile);
        // Here it ends

        MyScanner sc = new MyScanner();
        // MyScanner sc = new MyScanner(fileReader);

        out = new PrintWriter(new BufferedOutputStream(System.out)); // Output to console
        // out = new PrintWriter(new PrintStream(outputFile)); // Output to file

        getAns(sc);

        out.close();
    }

    private static void getAns(MyScanner sc){
        int n = sc.ni(), m = sc.ni();
        int[] k = sc.niArr0(n);
        HashMap<Integer, ArrayList<Integer>> map = new HashMap();

        for(int i = 0; i < m; i++){
            int day = sc.ni();
            map.putIfAbsent(day, new ArrayList<>());
            map.get(day).add(sc.ni());
        }

        int start = 1, end = 2 * (int)1e5;
        int ans = end;

//        out.println(map);

        while(start <= end){
            int mid = start + (end - start) / 2;
            if(OK(mid, map, Arrays.copyOf(k, n), n)){
                ans = mid;
                end = mid - 1;
            }else{
                start = mid + 1;
            }
        }

        out.println(ans);
    }

    private static boolean OK(int days, HashMap<Integer, ArrayList<Integer>> map, int[] k, int n){
        int cur = 0;
//        out.println(days);

        for(int i = 1; i <= days; i++){
            ++cur;
            ArrayList<Integer> index = map.get(i);
            if(index == null) continue;
            for(Integer in: index){
                if(cur == 0) break;
                int min = Math.min(cur, k[in - 1]);
                cur -= min;
                k[in - 1] -= min;
            }
        }

        for(int i = 0; i < n; i++) cur -= 2 * k[i];

        return cur >= 0;
    }
}

import java.io.*;
import java.util.*;

public class Codechef {

    static class MyScanner{
        BufferedReader br;
	StringTokenizer st;

	MyScanner(FileReader fileReader){
            br = new BufferedReader(fileReader);
	}

	MyScanner(){
            br = new BufferedReader(new InputStreamReader(System.in));
	}

	String nn(){
            while(st == null || !st.hasMoreElements()){
		try{
                    st = new StringTokenizer(br.readLine());
		}catch(IOException e){
                    e.printStackTrace();
		}
            }
            return st.nextToken();
	}

	char nc(){
            return nn().charAt(0);
	}

	int ni(){
            return Integer.parseInt(nn());
	}

	long nl(){
            return Long.parseLong(nn());
	}

	double nd(){
            return Double.parseDouble(nn());
	}

	int[] niArr0(int n){
            int[] ar = new int[n];
            for(int i = 0; i < n; i++) ar[i] = ni();
            return ar;
	}

        int[] niArr1(int n){
            int[] ar = new int[n + 1];
            for(int i = 1; i <= n; i++) ar[i] = ni();
            return ar;
	}

        long[] nlArr0(int n){
            long[] ar = new long[n];
            for(int i = 0; i < n; i++) ar[i] = nl();
            return ar;
        }

        long[] nlArr1(int n){
            long[] ar = new long[n + 1];
            for(int i = 1; i <= n; i++) ar[i] = nl();
            return ar;
        }
    }

    public static <T> void mprintln(T ... ar){
        for(T i: ar) out.print(i + " ");
        out.println();
    }

    private static PrintWriter out;

    public static void main(String[] args) throws FileNotFoundException{

        // Input from file
        // File inputFile = new File("JavaFile.txt");
        // File outputFile = new File("JavaOutputFile.txt");
        // FileReader fileReader = new FileReader(inputFile);
        // Here it ends

        MyScanner sc = new MyScanner();
        // MyScanner sc = new MyScanner(fileReader);

        out = new PrintWriter(new BufferedOutputStream(System.out)); // Output to console
        // out = new PrintWriter(new PrintStream(outputFile)); // Output to file

        getAns(sc);

        out.close();
    }

    private static void getAns(MyScanner sc){
        int n = sc.ni(), m = sc.ni();
        int[] k = sc.niArr0(n);
        HashMap<Integer, NavigableSet<Integer>> map = new HashMap();

        for(int i = 0; i < m; i++){
            int day = sc.ni(), type = sc.ni();
            map.putIfAbsent(type, new TreeSet());
            map.get(type).add(day);
        }

//        out.println(map);

        int start = 1, end = 2 * (int)1e5;
        int ans = end;

//        out.println(map);

        while(start <= end){
            int mid = start + end >> 1;
            if(OK(mid, getMapAccordingly(map, mid), Arrays.copyOf(k, n), n)){
                ans = mid;
                end = mid - 1;
            }else{
                start = mid + 1;
            }
        }

        out.println(ans);
    }

    private static HashMap<Integer, ArrayList<Integer>> getMapAccordingly(HashMap<Integer, NavigableSet<Integer>> map, int day){
        HashMap<Integer, ArrayList<Integer>> curMap = new HashMap();

        for(Integer in: map.keySet()){
            NavigableSet<Integer> set = map.get(in);
            Integer cur = set.floor(day);
            if(cur == null) continue;
            curMap.putIfAbsent(cur, new ArrayList<>());
            curMap.get(cur).add(in);
        }

//        out.println(day + " " + curMap);

        return curMap;
    }

    private static boolean OK(int days, HashMap<Integer, ArrayList<Integer>> map, int[] k, int n){
        int cur = 0;
//        out.println(days);

        for(int i = 1; i <= days; i++){
            ++cur;
            ArrayList<Integer> index = map.get(i);
            if(index == null) continue;
            for(Integer in: index){
                if(cur == 0) break;
                int min = Math.min(cur, k[in - 1]);
                cur -= min;
                k[in - 1] -= min;
            }
        }

        for(int i = 0; i < n; i++) cur -= 2 * k[i];

        return cur >= 0;
    }
}

//Created by Aminul on 5/14/2019.

import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Scanner;

public class F2 {
    static int maxn = (int) 2e5 + 5;
    static int n, m, f[], sum;
    static ArrayDeque<Integer> g[];

    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(System.in);
        PrintWriter pw = new PrintWriter(System.out);

        n = in.nextInt();
        m = in.nextInt();
        f = new int[n + 1];
        g = genDQ(maxn);
        sum = 0;

        for (int i = 1; i <= n; i++) {
            int k = in.nextInt();
            f[i] = k;
            sum += k;
        }

        for (int i = 0; i < m; i++) {
            int d = in.nextInt(), t = in.nextInt();
            g[d].add(t);
        }

        int ans = binarySearch();
        pw.println(ans);

        pw.close();
    }

    static int binarySearch() {
        int lo = 0, hi = maxn, mid;
        while (lo < hi) {
            mid = (lo + hi) / 2;
            if (check(mid)) hi = mid;
            else lo = mid + 1;
        }
        if (lo > 0 && check(lo - 1)) lo--;
        return lo;
    }

    static boolean check(int x) {
        int money = x;
        int rem = 2*sum - x;
        int frq[] = f.clone();
        for (int i = x; i >= 1; i--) {
            money = Math.min(money, i);
            for (int j : g[i]) {
                while (money > 0 && frq[j] > 0) {
                    money--;
                    frq[j]--;
                    rem--;
                }
            }
        }
        return rem <= 0;
    }

    static <T> ArrayDeque<T>[] genDQ(int n) {
        ArrayDeque<T> list[] = new ArrayDeque[n];
        for (int i = 0; i < n; i++) list[i] = new ArrayDeque<T>();
        return list;
    }

    static void debug(Object... obj) {
        System.err.println(Arrays.deepToString(obj));
    }
}

//Created by Aminul on 5/14/2019.

import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Scanner;

public class F2 {
    static int maxn = (int) 2e5 + 5;
    static int n, m, f[], sum;
    static ArrayDeque<Integer> g[];

    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(System.in);
        PrintWriter pw = new PrintWriter(System.out);

        n = in.nextInt();
        m = in.nextInt();
        f = new int[n + 1];
        g = genDQ(maxn);
        sum = 0;

        for (int i = 1; i <= n; i++) {
            int k = in.nextInt();
            f[i] = k;
            sum += k;
        }

        for (int i = 0; i < m; i++) {
            int d = in.nextInt(), t = in.nextInt();
            g[d].add(t);
        }

        int ans = binarySearch();
        pw.println(ans);

        pw.close();
    }

    static int binarySearch() {
        int lo = 0, hi = maxn, mid;
        while (lo < hi) {
            mid = (lo + hi) / 2;
            if (check(mid)) hi = mid;
            else lo = mid + 1;
        }
        if (lo > 0 && check(lo - 1)) lo--;
        return lo;
    }

    static boolean check(int x) {
        int money = x, saved = 0;
        int rem = sum;
        int frq[] = f.clone();
        for (int i = x; i >= 1; i--) {
            if (money + saved >= 2 * rem) return true;
            while (money > i) {
                money--;
                saved++;
            }
            for (int j : g[i]) {
                while (money > 0 && frq[j] > 0) {
                    money--;
                    frq[j]--;
                    rem--;
                    if (money + saved >= 2 * rem) return true;
                }
            }
            if (money + saved >= 2 * rem) return true;
        }
        return false;
    }

    static <T> ArrayDeque<T>[] genDQ(int n) {
        ArrayDeque<T> list[] = new ArrayDeque[n];
        for (int i = 0; i < n; i++) list[i] = new ArrayDeque<T>();
        return list;
    }

    static void debug(Object... obj) {
        System.err.println(Arrays.deepToString(obj));
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Washoum
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        inputClass in = new inputClass(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
        solver.solve(1, in, out);
        out.close();
    }

    static class F2MicrotransactionsHardVersion {
        static int n;
        static int m;
        static long sum;
        static int[] nb;
        static F2MicrotransactionsHardVersion.Pair[] promo;

        public void solve(int testNumber, inputClass sc, PrintWriter out) {
            n = sc.nextInt();
            m = sc.nextInt();
            nb = new int[n];
            sum = 0;
            for (int i = 0; i < n; i++) {
                nb[i] = sc.nextInt();
                sum += nb[i];
            }
            promo = new F2MicrotransactionsHardVersion.Pair[m];
            for (int i = 0; i < m; i++) {
                promo[i] = new F2MicrotransactionsHardVersion.Pair();
                promo[i].x = sc.nextInt();
                promo[i].y = sc.nextInt() - 1;
            }

            Arrays.sort(promo, new Comparator<F2MicrotransactionsHardVersion.Pair>() {

                public int compare(F2MicrotransactionsHardVersion.Pair a, F2MicrotransactionsHardVersion.Pair b) {
                    return Integer.compare(a.x, b.x);
                }
            });

            long l = 0;
            long r = (long) 1e18;
            long ans = 0;
            while (r - l >= 0) {
                long mid = (l + r) / 2;
                if (mid == 17) {
                    out.println();
                }
                if (check(mid)) {
                    ans = mid;
                    r = mid - 1;
                } else {
                    l = mid + 1;
                }
            }
            out.println(ans);
        }

        static boolean check(long mid) {
            if (mid >= 2 * sum) {
                return true;
            }
            if (mid < sum) {
                return false;
            }

            int[] each = Arrays.copyOf(nb, n);
            long kadeh = 0;
            int last = 0;
            for (int i = 0; i < m && promo[i].x <= mid; i++) {
                last = promo[i].x;
                if (i > 0) {
                    kadeh += promo[i].x - promo[i - 1].x;
                } else {
                    kadeh += promo[i].x;
                }
                if (i > 0) {
                    if (each[promo[i].y] > 0) {
                        if (each[promo[i].y] >= kadeh) {
                            each[promo[i].y] -= kadeh;
                            kadeh = 0;
                        } else {
                            kadeh -= each[promo[i].y];
                            each[promo[i].y] = 0;
                        }
                    }
                } else {
                    if (each[promo[i].y] > 0) {
                        if (each[promo[i].y] >= kadeh) {
                            each[promo[i].y] -= kadeh;
                            kadeh = 0;
                        } else {
                            kadeh -= each[promo[i].y];
                            each[promo[i].y] = 0;
                        }
                    }
                }
            }
            kadeh += mid - last;
            long rem = 0;
            for (int i = 0; i < n; i++) {
                rem += each[i];
            }
            if (kadeh >= rem * 2) {
                return true;
            } else {
                return false;
            }
        }

        static class Pair {
            int x;
            int y;

        }

    }

    static class inputClass {
        BufferedReader br;
        StringTokenizer st;

        public inputClass(InputStream in) {

            br = new BufferedReader(new InputStreamReader(in));
        }

        public String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Washoum
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        inputClass in = new inputClass(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
        solver.solve(1, in, out);
        out.close();
    }

    static class F2MicrotransactionsHardVersion {
        static int n;
        static int m;
        static long sum;
        static int[] nb;
        static F2MicrotransactionsHardVersion.Pair[] promo;

        public void solve(int testNumber, inputClass sc, PrintWriter out) {
            n = sc.nextInt();
            m = sc.nextInt();
            nb = new int[n];
            sum = 0;
            for (int i = 0; i < n; i++) {
                nb[i] = sc.nextInt();
                sum += nb[i];
            }
            promo = new F2MicrotransactionsHardVersion.Pair[m];
            for (int i = 0; i < m; i++) {
                promo[i] = new F2MicrotransactionsHardVersion.Pair();
                promo[i].x = sc.nextInt();
                promo[i].y = sc.nextInt() - 1;
            }

            Arrays.sort(promo, new Comparator<F2MicrotransactionsHardVersion.Pair>() {

                public int compare(F2MicrotransactionsHardVersion.Pair a, F2MicrotransactionsHardVersion.Pair b) {
                    return Integer.compare(a.x, b.x);
                }
            });

            long l = 0;
            long r = (long) 1e18;
            long ans = 0;
            while (r - l >= 0) {
                long mid = (l + r) / 2;
                if (mid == 17) {
                    out.println();
                }
                if (check(mid)) {
                    ans = mid;
                    r = mid - 1;
                } else {
                    l = mid + 1;
                }
            }
            out.println(ans);
        }

        static boolean check(long mid) {
            if (mid >= 2 * sum) {
                return true;
            }
            if (mid < sum) {
                return false;
            }
            int[] each = new int[n];
            System.arraycopy(nb, 0, each, 0, n);
            long kadeh = 0;
            int last = 0;
            for (int i = 0; i < m && promo[i].x <= mid; i++) {
                last = promo[i].x;
                if (i > 0) {
                    kadeh += promo[i].x - promo[i - 1].x;
                } else {
                    kadeh += promo[i].x;
                }

                if (each[promo[i].y] > 0) {
                    if (each[promo[i].y] >= kadeh) {
                        each[promo[i].y] -= kadeh;
                        kadeh = 0;
                    } else {
                        kadeh -= each[promo[i].y];
                        each[promo[i].y] = 0;
                    }
                }
            }
            kadeh += mid - last;
            long rem = 0;
            for (int i = 0; i < n; i++) {
                rem += each[i];
            }
            return kadeh >= rem * 2;
        }

        static class Pair {
            int x;
            int y;

        }

    }

    static class inputClass {
        BufferedReader br;
        StringTokenizer st;

        public inputClass(InputStream in) {

            br = new BufferedReader(new InputStreamReader(in));
        }

        public String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

import java.io.*;
import java.util.*;

public class tr0 {
	static PrintWriter out;
	static StringBuilder sb;
	static long mod =998244353;
    static int n,m,sum;
    static int[]a,ldays,ele;
    static pair []k;
	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner(System.in);
		out = new PrintWriter(System.out);
		n=sc.nextInt();
		m=sc.nextInt();
		a=new int[n];
		sum=0;
		for(int i=0;i<n;i++)
			sum+=a[i]=sc.nextInt();
	    k=new pair[m];
	    sum*=2;
	    ele=new int[n];
	    for(int i=0;i<m;i++) {
	    	int d=sc.nextInt();
	    	int x=sc.nextInt();
	    	ele[x-1]=Math.max(ele[x-1],d);
	    }
	    ldays=new int [500000];
	    for(int i=0;i<n;i++) {
	    	if(ele[i]!=0) {
	    		ldays[ele[i]-1]+=a[i];
	    	}
	    }
	    int lo=0;
	    int hi=sum;
	    int ans=0;
	    while(lo<=hi) {
	    	int mid=(lo+hi)/2;
	    	//out.println(mid);
	    	if(v(mid)) {
	    		hi=mid-1;
	    		ans=mid;
	    	//	out.println(mid);
	    	}
	    	else
	    		lo=mid+1;
	    }
	    out.println(ans);
		out.flush();
	}
     static boolean v(int m) {
    	 int to=0;
    	 int money=0;
    	 for(int i=0;i<m;i++) {
    		 money++;
    		 if(ldays[i]!=0) {
    			 if(money>=ldays[i]) {
    				 money-=ldays[i];
    				 to+=ldays[i];
    			 }
    			 else if(money<ldays[i]) {
    				 to+=money;
    				 money=0;
    			 }
    		 }
    	 }
    	// if(m==214)
    		// out.println("OO "+money+" "+to+" "+sum);
    	 if((sum-to*2)>money)
    		 return false;
    	 return true;
     }
	static public class segmentTree {
		int[] array, tree, lazy;
		int n;

		segmentTree(int[] aa) {
			array = aa;
			n = array.length - 1;
			tree = new int[n * 4];
			lazy = new int[n * 4];
			Arrays.fill(lazy, -1);
			build(1, 1, n);
		}

		public String toString() {
			return Arrays.toString(tree);
		}

		void build(int node, int l, int r) {
			if (l == r)
				tree[node] = array[r];
			else {
				int mid = (l + r) >> 1;
				build(node << 1, l, mid);
				build((node << 1) | 1, mid + 1, r);
				tree[node] = tree[node << 1] + tree[node << 1 | 1];
			}
		}

		void updateRange(int i, int j, int v) {
			updateR(1, 1, n, i, j, v);
		}

		void updateR(int node, int l, int r, int i, int j, int v) {
			if (i > r || j < l)
				return;
			if (i <= l && j >= r) {
				tree[node] = (r - l + 1) * v;
				lazy[node] = v;
			} else {
				int mid = l + r >> 1;
				propagate(node, l, mid, r);
				updateR(node << 1, l, mid, i, j, v);
				updateR(node << 1 | 1, mid + 1, r, i, j, v);
				tree[node] = tree[node << 1] + tree[node << 1 | 1];
			}
		}

		void propagate(int node, int b, int mid, int e) {
			if (lazy[node] != -1) {
				lazy[node << 1] = lazy[node];
				lazy[node << 1 | 1] = lazy[node];
				tree[node << 1] = (mid - b + 1) * lazy[node];
				tree[node << 1 | 1] = (e - mid) * lazy[node];
			}
			lazy[node] = -1;
		}

		int query(int i, int j) {
			return query(1, 1, n, i, j);
		}

		int query(int node, int b, int e, int i, int j) // O(log n)
		{
			if (i > e || j < b)
				return 0;
			if (b >= i && e <= j)
				return tree[node];
			int mid = b + e >> 1;
			propagate(node, b, mid, e);
			int q1 = query(node << 1, b, mid, i, j);
			int q2 = query(node << 1 | 1, mid + 1, e, i, j);
			return q1 + q2;

		}

	}

	static long fac(int n) {
		if (n == 0)
			return 1;
		if (n == 1)
			return 1;
		long ans = 1;
		for (int i = 1; i <= n; i++)
			ans = (i % mod * ans % mod) % mod;
		return ans % mod;
	}

	static long gcd(long a, long b) {

		if (b == 0)
			return a;
		return gcd(b, a % b);
	}

	static class pair implements Comparable<pair> {
		int d;
		int t;

		pair(int d,int t){
			this.d=d;
			this.t=t;
		}
		public String toString() {
			return t + " " + d;
		}

		public int compareTo(pair o) {
			return o.d - d;
		}
	}

	static class unionfind {
		int[] p;
		int[] size;

		unionfind(int n) {
			p = new int[n];
			size = new int[n];

			for (int i = 0; i < n; i++) {
				p[i] = i;
			}
			Arrays.fill(size, 1);
		}

		int findSet(int v) {
			if (v == p[v])
				return v;
			return p[v] = findSet(p[v]);
		}

		boolean sameSet(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return true;
			return false;
		}

		int max() {
			int max = 0;
			for (int i = 0; i < size.length; i++)
				if (size[i] > max)
					max = size[i];
			return max;
		}

		void combine(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return;
			if (size[a] > size[b]) {
				p[b] = a;
				size[a] += size[b];

			} else {
				p[a] = b;
				size[b] += size[a];
			}
		}
	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public String nextLine() throws IOException {
			return br.readLine();
		}

		public int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		public double nextDouble() throws IOException {
			return Double.parseDouble(next());
		}

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

		public Long nextLong() throws IOException {
			return Long.parseLong(next());
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main
{
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
    static class Pair implements Comparable<Pair> {
        int x,y;
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
        public int compareTo(Pair o) {
            if(x!=o.x)
                return x-o.x;
            return this.y - o.y;
        }
        public int hashCode() {
            return (int)(1L*1000000000*x + y)%1000000007;
        }
        public boolean equals(Object o) {
            if(o instanceof Pair) {
                Pair other = (Pair)o;
                return other.hashCode()==this.hashCode();
            }
            else return false;
        }
        public String toString(){
            return x+" "+y;
        }
    }
    //static Scanner sc = new Scanner(System.in);
    static Reader sc = new Reader();
    static StringBuilder sb = new StringBuilder();
    static PrintWriter pw = new PrintWriter(System.out,true);
    public static void main(String[] args) throws IOException {
        //Code start from here
        int n = sc.nextInt(),m = sc.nextInt();
        HashMap<Integer,Integer> hm = new HashMap<>();
        long left=0;
        for(int i =1;i<=n;i++){
            int val = sc.nextInt();
            hm.put(i,val);
            left+=val;
        }
        ArrayList<Pair> set = new ArrayList<>();
        for(int i =0;i<m;i++) {
            set.add(new Pair(sc.nextInt(),sc.nextInt()));
        }
        Collections.sort(set);
        long rem=0,coin=0;
        for(int i =m-1;i>=0;i--) {
            Pair p = set.get(i);
            if(hm.get(p.y)>0) {
                if(left*2 < p.x && i ==m-1) {
                    System.out.println(left*2);
                    System.exit(0);
                }
                if(coin==0)
                    coin = p.x;
                coin = min(coin,p.x);
                if(hm.get(p.y)<=coin) {
                    coin-=hm.get(p.y);
                    left-=hm.get(p.y);
                    rem+=hm.get(p.y);
                    hm.put(p.y,0);
                   // System.out.println("if"+rem);
                } else {
                    left-=coin;
                    rem+=coin;
                    coin=0;
                    //System.out.println("else"+rem);
                }
                if(coin ==0)
                    break;
                //System.out.println("offer pair "+p);
                //System.out.println("left = "+ left +"    coins  = "+coin+" removed = "+rem);

            }
        }
        //System.out.println("left = "+ left +"    coins  = "+coin+" removed = "+rem);
        long val = (left*2)+rem;
        System.out.println(val);

        pw.println(sb);
        pw.flush();
        pw.close();
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main
{
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
    static class Pair implements Comparable<Pair> {
        int x,y;
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
        public int compareTo(Pair o) {
            if(x!=o.x)
                return x-o.x;
            return this.y - o.y;
        }
        public int hashCode() {
            return (int)(1L*1000000000*x + y)%1000000007;
        }
        public boolean equals(Object o) {
            if(o instanceof Pair) {
                Pair other = (Pair)o;
                return other.hashCode()==this.hashCode();
            }
            else return false;
        }
        public String toString(){
            return x+" "+y;
        }
    }
    //static Scanner sc = new Scanner(System.in);
    static Reader sc = new Reader();
    static StringBuilder sb = new StringBuilder();
    static PrintWriter pw = new PrintWriter(System.out,true);
    public static void main(String[] args) throws IOException {
        //Code start from here
        int n = sc.nextInt(),m = sc.nextInt();
        HashMap<Integer,Integer> hm = new HashMap<>();
        long total=0;
        for(int i =1;i<=n;i++){
            int val = sc.nextInt();
            hm.put(i,val);
            total+=val;
        }
        ArrayList<Pair> set = new ArrayList<>();
        for(int i =0;i<m;i++) {
            set.add(new Pair(sc.nextInt(),sc.nextInt()));
        }
        Collections.sort(set);
        int coin = set.get(m-1).x;
        for(int i =m-1;i>=0;i--) {
            Pair p = set.get(i);
            if(hm.get(p.y)>0) {
                if(hm.get(p.y)<=coin) {
                    coin-=hm.get(p.y);
                    total-=hm.get(p.y);
                } else {
                    total-=coin;
                    break;
                }
            }
           // System.out.println(coin+"  pair "+p);
        }
        long val=0;
        if(coin %2!=0)
            val=1;

        coin/=2;
        total-=coin;
        val += set.get(m-1).x + total * 2 ;
        sb.append(val);

        pw.println(sb);
        pw.flush();
        pw.close();
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main
{
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
    static class Pair implements Comparable<Pair> {
        int x,y;
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
        public int compareTo(Pair o) {
            if(x!=o.x)
                return x-o.x;
            return this.y - o.y;
        }
        public int hashCode() {
            return (int)(1L*1000000000*x + y)%1000000007;
        }
        public boolean equals(Object o) {
            if(o instanceof Pair) {
                Pair other = (Pair)o;
                return other.hashCode()==this.hashCode();
            }
            else return false;
        }
        public String toString(){
            return x+" "+y;
        }
    }
    //static Scanner sc = new Scanner(System.in);
    static Reader sc = new Reader();
    static StringBuilder sb = new StringBuilder();
    static PrintWriter pw = new PrintWriter(System.out,true);
    public static void main(String[] args) throws IOException {
        //Code start from here
        int n = sc.nextInt(),m = sc.nextInt();
        HashMap<Integer,Integer> hm = new HashMap<>();
        long left=0;
        for(int i =1;i<=n;i++){
            int val = sc.nextInt();
            hm.put(i,val);
            left+=val;
        }
        ArrayList<Pair> set = new ArrayList<>();
        for(int i =0;i<m;i++) {
            set.add(new Pair(sc.nextInt(),sc.nextInt()));
        }
        Collections.sort(set);
        long rem=0,coin=0;
        for(int i =m-1;i>=0;i--) {
            Pair p = set.get(i);
            if(hm.get(p.y)>0) {
                if(left*2 < p.x && coin ==0) {
                    System.out.println(left*2);
                    System.exit(0);
                }
                if(coin==0)
                    coin = p.x;
                coin = min(coin,p.x);
                if(hm.get(p.y)<=coin) {
                    coin-=hm.get(p.y);
                    left-=hm.get(p.y);
                    rem+=hm.get(p.y);
                    hm.put(p.y,0);
                   // System.out.println("if"+rem);
                } else {
                    left-=coin;
                    rem+=coin;
                    coin=0;
                    //System.out.println("else"+rem);
                }
                if(coin ==0)
                    break;
                //System.out.println("offer pair "+p);
                //System.out.println("left = "+ left +"    coins  = "+coin+" removed = "+rem);

            }
        }
        //System.out.println("left = "+ left +"    coins  = "+coin+" removed = "+rem);
        long val = (left*2)+rem;
        System.out.println(val);

        pw.println(sb);
        pw.flush();
        pw.close();
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main
{
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
    static class Pair implements Comparable<Pair> {
        int x,y;
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
        public int compareTo(Pair o) {
            if(x!=o.x)
                return x-o.x;
            return this.y - o.y;
        }
        public int hashCode() {
            return (int)(1L*1000000000*x + y)%1000000007;
        }
        public boolean equals(Object o) {
            if(o instanceof Pair) {
                Pair other = (Pair)o;
                return other.hashCode()==this.hashCode();
            }
            else return false;
        }
        public String toString(){
            return x+" "+y;
        }
    }
    //static Scanner sc = new Scanner(System.in);
    static Reader sc = new Reader();
    static StringBuilder sb = new StringBuilder();
    static PrintWriter pw = new PrintWriter(System.out,true);
    public static void main(String[] args) throws IOException {
        //Code start from here
        int n = sc.nextInt(),m = sc.nextInt();
        HashMap<Integer,Integer> hm = new HashMap<>();
        long left=0;
        for(int i =1;i<=n;i++){
            int val = sc.nextInt();
            hm.put(i,val);
            left+=val;
        }
        ArrayList<Pair> set = new ArrayList<>();
        for(int i =0;i<m;i++) {
            set.add(new Pair(sc.nextInt(),sc.nextInt()));
        }
        Collections.sort(set);
        int coin = 0;
        if(left*2<coin) {
            System.out.println(left*2);
            System.exit(0);
        }
        long rem=0;
        for(int i =m-1;i>=0;i--) {
            Pair p = set.get(i);
            if(hm.get(p.y)>0) {
                if(coin==0)
                    coin = p.x;
                if(hm.get(p.y)<=coin) {
                    coin-=hm.get(p.y);
                    left-=hm.get(p.y);
                    rem+=hm.get(p.y);
                    hm.put(p.y,0);
                   // System.out.println("if"+rem);
                } else {
                    left-=coin;
                    rem+=coin;
                    coin=0;
                    //System.out.println("else"+rem);
                }
                if(coin ==0)
                    break;
                //System.out.println("offer pair "+p);
               // System.out.println("left = "+ left +"    coins  = "+coin+" removed = "+rem);

            }
        }
        //System.out.println("left = "+ left +"    coins  = "+coin+" removed = "+rem);
        long val = (left*2)+rem;
        System.out.println(val);

        pw.println(sb);
        pw.flush();
        pw.close();
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main
{
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
    static class Pair implements Comparable<Pair> {
        int x,y;
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
        public int compareTo(Pair o) {
            if(x!=o.x)
                return x-o.x;
            return this.y - o.y;
        }
        public int hashCode() {
            return (int)(1L*1000000000*x + y)%1000000007;
        }
        public boolean equals(Object o) {
            if(o instanceof Pair) {
                Pair other = (Pair)o;
                return other.hashCode()==this.hashCode();
            }
            else return false;
        }
        public String toString(){
            return x+" "+y;
        }
    }
    //static Scanner sc = new Scanner(System.in);
    static Reader sc = new Reader();
    static StringBuilder sb = new StringBuilder();
    static PrintWriter pw = new PrintWriter(System.out,true);
    public static void main(String[] args) throws IOException {
        //Code start from here
        int n = sc.nextInt(),m = sc.nextInt();
        int arr[]= new int[n+1];
        long left=0,rem=0,burle=0,prev_offer_day=0;
        for(int i =1;i<=n;i++){
            arr[i]= sc.nextInt();
            left+=arr[i];
        }
        ArrayList<Pair> al = new ArrayList<>();
        for(int i =0;i<m;i++) {
            al.add(new Pair(sc.nextInt(),sc.nextInt()));
        }
        Collections.sort(al);
        for(int i =0;i<m;i++){
            Pair p = al.get(i);
            if(arr[p.y]>0) {
                if(p.x>=2*left)
                    break;
                burle += p.x-prev_offer_day;
                if(arr[p.y]<=burle) {
                    burle-=arr[p.y];
                    left-=arr[p.y];
                    rem+=arr[p.y];
                    arr[p.y]=0;
                    //System.out.println("if"+rem);
                } else {
                    left-=burle;
                    rem+=burle;
                    burle=0;
                    //System.out.println("else"+rem);
                }
                prev_offer_day = p.x;
            }
           // System.out.println("offer pair "+p);
            //System.out.println("left = "+ left +"    coins  = "+burle+" removed = "+rem);
        }

        //System.out.println("left = "+ left +"    coins  = "+burle+" removed = "+rem);
        long val = (left*2)+rem;
        sb.append(val);
        pw.println(sb);
        pw.flush();
        pw.close();
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main
{
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
    static class Pair implements Comparable<Pair> {
        int x,y;
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
        public int compareTo(Pair o) {
            if(x!=o.x)
                return x-o.x;
            return this.y - o.y;
        }
        public int hashCode() {
            return (int)(1L*1000000000*x + y)%1000000007;
        }
        public boolean equals(Object o) {
            if(o instanceof Pair) {
                Pair other = (Pair)o;
                return other.hashCode()==this.hashCode();
            }
            else return false;
        }
        public String toString(){
            return x+" "+y;
        }
    }
    //static Scanner sc = new Scanner(System.in);
    static Reader sc = new Reader();
    static StringBuilder sb = new StringBuilder();
    static PrintWriter pw = new PrintWriter(System.out,true);
    public static void main(String[] args) throws IOException {
        //Code start from here
        int n = sc.nextInt(),m = sc.nextInt();
        HashMap<Integer,Integer> hm = new HashMap<>();
        long total=0;
        for(int i =1;i<=n;i++){
            int val = sc.nextInt();
            hm.put(i,val);
            total+=val;
        }
        ArrayList<Pair> set = new ArrayList<>();
        for(int i =0;i<m;i++) {
            set.add(new Pair(sc.nextInt(),sc.nextInt()));
        }
        Collections.sort(set);
        int coin = set.get(m-1).x;
        if(total*2<coin) {
            System.out.println(total*2);
            System.exit(0);
        }
        for(int i =m-1;i>=0;i--) {
            Pair p = set.get(i);
            if(hm.get(p.y)>0) {
                if(hm.get(p.y)<=coin) {
                    coin-=hm.get(p.y);
                    total-=hm.get(p.y);
                    hm.put(p.y,0);
                } else {
                    total-=coin;
                    break;
                }
            }
           // System.out.println(coin+"  pair "+p);
        }
        long val=0;
        if(coin %2!=0)
            val=1;
        if(set.get(m-1).x==coin) {
            val=-coin;
        }else {
            coin /= 2;
            total -= coin;
        }
        //System.out.println(total+"   set val="+set.get(m-1).x);
        val += set.get(m-1).x + total * 2 ;
        sb.append(val);

        pw.println(sb);
        pw.flush();
        pw.close();
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main
{
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
    static class Pair implements Comparable<Pair> {
        int x,y;
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
        public int compareTo(Pair o) {
            if(x!=o.x)
                return x-o.x;
            return this.y - o.y;
        }
        public int hashCode() {
            return (int)(1L*1000000000*x + y)%1000000007;
        }
        public boolean equals(Object o) {
            if(o instanceof Pair) {
                Pair other = (Pair)o;
                return other.hashCode()==this.hashCode();
            }
            else return false;
        }
        public String toString(){
            return x+" "+y;
        }
    }
    //static Scanner sc = new Scanner(System.in);
    static Reader sc = new Reader();
    static StringBuilder sb = new StringBuilder();
    static PrintWriter pw = new PrintWriter(System.out,true);
    public static void main(String[] args) throws IOException {
        //Code start from here
        int n = sc.nextInt(),m = sc.nextInt();
        HashMap<Integer,Integer> hm = new HashMap<>();
        long left=0;
        for(int i =1;i<=n;i++){
            int val = sc.nextInt();
            hm.put(i,val);
            left+=val;
        }
        ArrayList<Pair> set = new ArrayList<>();
        for(int i =0;i<m;i++) {
            set.add(new Pair(sc.nextInt(),sc.nextInt()));
        }
        Collections.sort(set);
        //sorting according to date
        long rem=0,coin=0;
        //left is number of total figure needed     rem is bought during sale
        for(int i =m-1;i>=0;i--) {
            Pair p = set.get(i);
            //accessing date in reverse order
            if(hm.get(p.y)>0) {
                //figure we need to buy

                //if day > 2*total need to buy  and coin ==0 is used to check that
                // we havent bought anything yet
                if(left*2 < p.x && coin ==0) {
                    System.out.println(left*2);
                    System.exit(0);
                }
                //initialise coin to last day of sale
                if(coin==0)
                    coin = p.x;
                //coin should be less <= the day of sale according to spenditure
                coin = min(coin,p.x);
                //spending of coin
                if(hm.get(p.y)<=coin) {
                    coin-=hm.get(p.y);
                    left-=hm.get(p.y);
                    rem+=hm.get(p.y);
                    hm.put(p.y,0);
                   // System.out.println("if"+rem);
                } else {
                    left-=coin;
                    rem+=coin;
                    coin=0;
                    //System.out.println("else"+rem);
                }
                if(coin ==0)
                    break;
                //System.out.println("offer pair "+p);
                //System.out.println("left = "+ left +"    coins  = "+coin+" removed = "+rem);

            }
        }
        //System.out.println("left = "+ left +"    coins  = "+coin+" removed = "+rem);
        long val = (left*2)+rem;
        System.out.println(val);

        pw.println(sb);
        pw.flush();
        pw.close();
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main
{
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
    static class Pair implements Comparable<Pair> {
        int x,y;
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
        public int compareTo(Pair o) {
            if(x!=o.x)
                return x-o.x;
            return this.y - o.y;
        }
        public int hashCode() {
            return (int)(1L*1000000000*x + y)%1000000007;
        }
        public boolean equals(Object o) {
            if(o instanceof Pair) {
                Pair other = (Pair)o;
                return other.hashCode()==this.hashCode();
            }
            else return false;
        }
        public String toString(){
            return x+" "+y;
        }
    }
    //static Scanner sc = new Scanner(System.in);
    static Reader sc = new Reader();
    static StringBuilder sb = new StringBuilder();
    static PrintWriter pw = new PrintWriter(System.out,true);
    public static void main(String[] args) throws IOException {
        //Code start from here
        int n = sc.nextInt(),m = sc.nextInt();
        int arr[]= new int[n+1];
        long left=0,rem=0,burle=0,prev_offer_day=0;
        for(int i =1;i<=n;i++){
            arr[i]= sc.nextInt();
            left+=arr[i];
        }
        ArrayList<Pair> al = new ArrayList<>();
        for(int i =0;i<m;i++) {
            al.add(new Pair(sc.nextInt(),sc.nextInt()));
        }
        Collections.sort(al);
        for(int i =0;i<m;i++){
            Pair p = al.get(i);
            if(arr[p.y]>0) {
                if(p.x>=2*left)
                    break;
                burle += p.x-prev_offer_day;
                if(arr[p.y]<burle) {
                    burle-=arr[p.y];
                    left-=arr[p.y];
                    rem+=arr[p.y];
                    arr[p.y]=0;
                    //System.out.println("if"+rem);
                } else {
                    left-=burle;
                    rem+=burle;
                    burle=0;
                    //System.out.println("else"+rem);
                }
                prev_offer_day = p.x;
            }
            //System.out.println("offer pair "+p);
           // System.out.println("left = "+ left +"    coins  = "+burle+" removed = "+rem);
        }
        if(left > 0 && burle > 0) {
            if(burle >= 2*left) {
                burle = 2 * left;
                left = 0;
            } else {
                left-=burle/2;
                burle = -(burle%2);
            }
        }
        //System.out.println("left = "+ left +"    coins  = "+burle+" removed = "+rem);
        long val = (left*2)+rem+burle;
        sb.append(val);
        pw.println(sb);
        pw.flush();
        pw.close();
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main
{
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
    static class Pair implements Comparable<Pair> {
        int x,y;
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
        public int compareTo(Pair o) {
            if(x!=o.x)
                return x-o.x;
            return this.y - o.y;
        }
        public int hashCode() {
            return (int)(1L*1000000000*x + y)%1000000007;
        }
        public boolean equals(Object o) {
            if(o instanceof Pair) {
                Pair other = (Pair)o;
                return other.hashCode()==this.hashCode();
            }
            else return false;
        }
        public String toString(){
            return x+" "+y;
        }
    }
    //static Scanner sc = new Scanner(System.in);
    static Reader sc = new Reader();
    static StringBuilder sb = new StringBuilder();
    static PrintWriter pw = new PrintWriter(System.out,true);
    public static void main(String[] args) throws IOException {
        //Code start from here
        int n = sc.nextInt(),m = sc.nextInt();
        HashMap<Integer,Integer> hm = new HashMap<>();
        long total=0;
        for(int i =1;i<=n;i++){
            int val = sc.nextInt();
            hm.put(i,val);
            total+=val;
        }
        ArrayList<Pair> set = new ArrayList<>();
        for(int i =0;i<m;i++) {
            set.add(new Pair(sc.nextInt(),sc.nextInt()));
        }
        Collections.sort(set);
        int coin = set.get(m-1).x;
        if(total*2<=coin) {
            System.out.println(total*2);
            System.exit(0);
        }
        for(int i =m-1;i>=0;i--) {
            Pair p = set.get(i);
            if(hm.get(p.y)>0) {
                if(hm.get(p.y)<=coin) {
                    coin-=hm.get(p.y);
                    total-=hm.get(p.y);
                    hm.put(p.y,0);
                } else {
                    total-=coin;
                    break;
                }
            }
           // System.out.println(coin+"  pair "+p);
        }
        long val=0;
        if(coin %2!=0)
            val=1;
        if(set.get(m-1).x==coin) {
            val=-coin;
        }else {
            coin /= 2;
            total -= coin;
        }
        //System.out.println(total+"   set val="+set.get(m-1).x);
        val += set.get(m-1).x + total * 2 ;
        sb.append(val);

        pw.println(sb);
        pw.flush();
        pw.close();
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main
{
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
    static class Pair implements Comparable<Pair> {
        int x,y;
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
        public int compareTo(Pair o) {
            if(x!=o.x)
                return x-o.x;
            return this.y - o.y;
        }
        public int hashCode() {
            return (int)(1L*1000000000*x + y)%1000000007;
        }
        public boolean equals(Object o) {
            if(o instanceof Pair) {
                Pair other = (Pair)o;
                return other.hashCode()==this.hashCode();
            }
            else return false;
        }
        public String toString(){
            return x+" "+y;
        }
    }
    //static Scanner sc = new Scanner(System.in);
    static Reader sc = new Reader();
    static StringBuilder sb = new StringBuilder();
    static PrintWriter pw = new PrintWriter(System.out,true);
    public static void main(String[] args) throws IOException {
        //Code start from here
        int n = sc.nextInt(),m = sc.nextInt();
        HashMap<Integer,Integer> hm = new HashMap<>();
        long total=0;
        for(int i =1;i<=n;i++){
            int val = sc.nextInt();
            hm.put(i,val);
            total+=val;
        }
        ArrayList<Pair> set = new ArrayList<>();
        for(int i =0;i<m;i++) {
            set.add(new Pair(sc.nextInt(),sc.nextInt()));
        }
        Collections.sort(set);
        int coin = set.get(m-1).x;
        for(int i =m-1;i>=0;i--) {
            Pair p = set.get(i);
            if(hm.get(p.y)>0) {
                if(hm.get(p.y)<=coin) {
                    coin-=hm.get(p.y);
                    total-=hm.get(p.y);
                    hm.put(p.y,0);
                } else {
                    total-=coin;
                    break;
                }
            }
           // System.out.println(coin+"  pair "+p);
        }
        long val=0;
        if(coin %2!=0)
            val=1;
        if(set.get(m-1).x==coin) {
            val=-coin;
        }else {
            coin /= 2;
            total -= coin;
        }
        //System.out.println(total+"   set val="+set.get(m-1).x);
        val += set.get(m-1).x + total * 2 ;
        sb.append(val);

        pw.println(sb);
        pw.flush();
        pw.close();
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main
{
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
    static class Pair implements Comparable<Pair> {
        int x,y;
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
        public int compareTo(Pair o) {
            if(x!=o.x)
                return x-o.x;
            return this.y - o.y;
        }
        public int hashCode() {
            return (int)(1L*1000000000*x + y)%1000000007;
        }
        public boolean equals(Object o) {
            if(o instanceof Pair) {
                Pair other = (Pair)o;
                return other.hashCode()==this.hashCode();
            }
            else return false;
        }
        public String toString(){
            return x+" "+y;
        }
    }
    //static Scanner sc = new Scanner(System.in);
    static Reader sc = new Reader();
    static StringBuilder sb = new StringBuilder();
    static PrintWriter pw = new PrintWriter(System.out,true);
    public static void main(String[] args) throws IOException {
        //Code start from here
        int n = sc.nextInt(),m = sc.nextInt();
        HashMap<Integer,Integer> hm = new HashMap<>();
        long left=0;
        for(int i =1;i<=n;i++){
            int val = sc.nextInt();
            hm.put(i,val);
            left+=val;
        }
        ArrayList<Pair> set = new ArrayList<>();
        for(int i =0;i<m;i++) {
            set.add(new Pair(sc.nextInt(),sc.nextInt()));
        }
        Collections.sort(set);
        int coin = 0;
        if(left*2<coin) {
            System.out.println(left*2);
            System.exit(0);
        }
        long rem=0;
        for(int i =m-1;i>=0;i--) {
            Pair p = set.get(i);
            if(hm.get(p.y)>0) {
                if(coin==0)
                    coin = p.x;
                coin = min(coin,p.x);
                if(hm.get(p.y)<=coin) {
                    coin-=hm.get(p.y);
                    left-=hm.get(p.y);
                    rem+=hm.get(p.y);
                    hm.put(p.y,0);
                   // System.out.println("if"+rem);
                } else {
                    left-=coin;
                    rem+=coin;
                    coin=0;
                    //System.out.println("else"+rem);
                }
                if(coin ==0)
                    break;
                //System.out.println("offer pair "+p);
                //System.out.println("left = "+ left +"    coins  = "+coin+" removed = "+rem);

            }
        }
        //System.out.println("left = "+ left +"    coins  = "+coin+" removed = "+rem);
        long val = (left*2)+rem;
        System.out.println(val);

        pw.println(sb);
        pw.flush();
        pw.close();
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main
{
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
    static class Pair implements Comparable<Pair> {
        int x,y;
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
        public int compareTo(Pair o) {
            if(x!=o.x)
                return x-o.x;
            return this.y - o.y;
        }
        public int hashCode() {
            return (int)(1L*1000000000*x + y)%1000000007;
        }
        public boolean equals(Object o) {
            if(o instanceof Pair) {
                Pair other = (Pair)o;
                return other.hashCode()==this.hashCode();
            }
            else return false;
        }
        public String toString(){
            return x+" "+y;
        }
    }
    //static Scanner sc = new Scanner(System.in);
    static Reader sc = new Reader();
    static StringBuilder sb = new StringBuilder();
    static PrintWriter pw = new PrintWriter(System.out,true);
    public static void main(String[] args) throws IOException {
        //Code start from here
        int n = sc.nextInt(),m = sc.nextInt();
        HashMap<Integer,Integer> hm = new HashMap<>();
        long total=0;
        for(int i =1;i<=n;i++){
            int val = sc.nextInt();
            hm.put(i,val);
            total+=val;
        }
        ArrayList<Pair> set = new ArrayList<>();
        for(int i =0;i<m;i++) {
            set.add(new Pair(sc.nextInt(),sc.nextInt()));
        }
        Collections.sort(set);
        int coin = set.get(m-1).x;
        if(total*2<coin) {
            System.out.println(total*2);
            System.exit(0);
        }
        long rem=0;
        for(int i =m-1;i>=0;i--) {
            Pair p = set.get(i);
            if(hm.get(p.y)>0) {
                if(hm.get(p.y)<=coin) {
                    coin-=hm.get(p.y);
                    total-=hm.get(p.y);
                    rem+=hm.get(p.y);
                    hm.put(p.y,0);
                   // System.out.println("if"+rem);
                } else {
                    total-=coin;
                    rem+=coin;
                    coin=0;
                    //System.out.println("else"+rem);
                    break;
                }
            }
           //System.out.println(coin+"  pair "+p);
        }
        //System.out.println("left = "+ total +"    coins  = "+coin+" removed = "+rem);
        long val = (total*2)+rem;
        System.out.println(val);

        pw.println(sb);
        pw.flush();
        pw.close();
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main
{
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
    static class Pair implements Comparable<Pair> {
        int x,y;
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
        public int compareTo(Pair o) {
            if(x!=o.x)
                return x-o.x;
            return this.y - o.y;
        }
        public int hashCode() {
            return (int)(1L*1000000000*x + y)%1000000007;
        }
        public boolean equals(Object o) {
            if(o instanceof Pair) {
                Pair other = (Pair)o;
                return other.hashCode()==this.hashCode();
            }
            else return false;
        }
        public String toString(){
            return x+" "+y;
        }
    }
    //static Scanner sc = new Scanner(System.in);
    static Reader sc = new Reader();
    static StringBuilder sb = new StringBuilder();
    static PrintWriter pw = new PrintWriter(System.out,true);
    public static void main(String[] args) throws IOException {
        //Code start from here
        int n = sc.nextInt(),m = sc.nextInt();
        int arr[]= new int[n+1];
        long left=0,rem=0,burle=0,prev_offer_day=0;
        for(int i =1;i<=n;i++){
            arr[i]= sc.nextInt();
            left+=arr[i];
        }
        ArrayList<Pair> al = new ArrayList<>();
        for(int i =0;i<m;i++) {
            al.add(new Pair(sc.nextInt(),sc.nextInt()));
        }
        Collections.sort(al);
        for(int i =0;i<m;i++){
            Pair p = al.get(i);
            if(arr[p.y]>0) {
                if(p.x>=2*left)
                    break;
                burle += p.x-prev_offer_day;
                if(arr[p.y]<burle) {
                    burle-=arr[p.y];
                    left-=arr[p.y];
                    rem+=arr[p.y];
                    arr[p.y]=0;
                    //System.out.println("if"+rem);
                } else {
                    left-=burle;
                    rem+=burle;
                    burle=0;
                    //System.out.println("else"+rem);
                }
                prev_offer_day = p.x;
            }
            //System.out.println("offer pair "+p);
           // System.out.println("left = "+ left +"    coins  = "+burle+" removed = "+rem);
        }
        if(left > 0 && burle > 0) {
            burle = - burle;
        }
        //System.out.println("left = "+ left +"    coins  = "+burle+" removed = "+rem);
        long val = (left*2)+rem+burle;
        sb.append(val);
        pw.println(sb);
        pw.flush();
        pw.close();
    }
}

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main
{
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
    static class Pair implements Comparable<Pair> {
        int x,y;
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
        public int compareTo(Pair o) {
            if(x!=o.x)
                return x-o.x;
            return this.y - o.y;
        }
        public int hashCode() {
            return (int)(1L*1000000000*x + y)%1000000007;
        }
        public boolean equals(Object o) {
            if(o instanceof Pair) {
                Pair other = (Pair)o;
                return other.hashCode()==this.hashCode();
            }
            else return false;
        }
        public String toString(){
            return x+" "+y;
        }
    }
    //static Scanner sc = new Scanner(System.in);
    static Reader sc = new Reader();
    static StringBuilder sb = new StringBuilder();
    static PrintWriter pw = new PrintWriter(System.out,true);
    public static void main(String[] args) throws IOException {
        //Code start from here
        int n = sc.nextInt(),m = sc.nextInt();
        HashMap<Integer,Integer> hm = new HashMap<>();
        long total=0;
        for(int i =1;i<=n;i++){
            int val = sc.nextInt();
            hm.put(i,val);
            total+=val;
        }
        ArrayList<Pair> set = new ArrayList<>();
        for(int i =0;i<m;i++) {
            set.add(new Pair(sc.nextInt(),sc.nextInt()));
        }
        Collections.sort(set);
        int coin = set.get(m-1).x;
        for(int i =m-1;i>=0;i--) {
            Pair p = set.get(i);
            if(hm.get(p.y)>0) {
                if(hm.get(p.y)<=coin) {
                    coin-=hm.get(p.y);
                    total-=hm.get(p.y);
                    hm.put(p.y,0);
                } else {
                    total-=coin;
                    break;
                }
            }
           // System.out.println(coin+"  pair "+p);
        }
        long val=0;
        if(coin %2!=0)
            val=1;

        coin/=2;
        total-=coin;
        val += set.get(m-1).x + total * 2 ;
        sb.append(val);

        pw.println(sb);
        pw.flush();
        pw.close();
    }
}

import java.util.*;
import java.io.*;
import java.text.*;
public class Main{
    //SOLUTION BEGIN
    //This code is not meant for understanding, you have been warned.
    void pre() throws Exception{}
    void solve(int TC) throws Exception{
        int n = ni(), m = ni();
        int[] count = new int[n];
        for(int i = 0; i< n; i++)count[i] = ni();
        int[] offer = new int[n];
        for(int i = 0; i< m; i++){
            int d = ni(), t = ni()-1;
            offer[t] = Math.max(offer[t], d);
        }
        int[] cnt = new int[MX];
        for(int i = 0; i< n; i++)cnt[offer[i]]++;
        int[][] g = new int[MX][];
        for(int i = 0; i< MX; i++)g[i] = new int[cnt[i]];
        for(int i = 0; i< n; i++)g[offer[i]][--cnt[offer[i]]] = i;
        int lo = 0, hi = MX-1;
        while(lo+1<hi){
            int mid = lo+(hi-lo)/2;
            if(check(count, g, mid))hi = mid;
            else lo = mid;
        }
        if(check(count,g,lo))hi = lo;
        pn(hi);
    }
    boolean check(int[] count, int[][] offer, int days){
        long coin = 0;
        long rem = 0;
        for(int i:offer[0])rem+=2*count[i];
        for(int i = days+1; i< MX; i++)for(int x:offer[i])rem+=2*count[x];
        for(int cur = 1; cur<= days; cur++){
            coin+=1;
            for(int i:offer[cur]){
                long mn = Math.min(coin, count[i]);
                rem+=2*(count[i]-mn);
                coin-=mn;
            }
        }
        return coin>=rem;
    }
    //SOLUTION END
    void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
    long mod = (long)998244353, IINF = (long)1e18;
    final int INF = (int)1e9, MX = (int)5e5+1;
    DecimalFormat df = new DecimalFormat("0.00000000000");
    double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8;
    static boolean multipleTC = false, memory = false;
    FastReader in;PrintWriter out;
    void run() throws Exception{
        in = new FastReader();
        out = new PrintWriter(System.out);
        //Solution Credits: Taranpreet Singh
        int T = (multipleTC)?ni():1;
        pre();for(int t = 1; t<= T; t++)solve(t);
        out.flush();
        out.close();
    }
    public static void main(String[] args) throws Exception{
        if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
        else new Main().run();
    }
    long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
    int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
    int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
    void p(Object o){out.print(o);}
    void pn(Object o){out.println(o);}
    void pni(Object o){out.println(o);out.flush();}
    String n()throws Exception{return in.next();}
    String nln()throws Exception{return in.nextLine();}
    int ni()throws Exception{return Integer.parseInt(in.next());}
    long nl()throws Exception{return Long.parseLong(in.next());}
    double nd()throws Exception{return Double.parseDouble(in.next());}

    class FastReader{
        BufferedReader br;
        StringTokenizer st;
        public FastReader(){
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public FastReader(String s) throws Exception{
            br = new BufferedReader(new FileReader(s));
        }

        String next() throws Exception{
            while (st == null || !st.hasMoreElements()){
                try{
                    st = new StringTokenizer(br.readLine());
                }catch (IOException  e){
                    throw new Exception(e.toString());
                }
            }
            return st.nextToken();
        }

        String nextLine() throws Exception{
            String str = "";
            try{
                str = br.readLine();
            }catch (IOException e){
                throw new Exception(e.toString());
            }
            return str;
        }
    }
}

import java.util.*;
import java.io.*;
import java.text.*;
public class Main{
    //SOLUTION BEGIN
    //This code is not meant for understanding, you have been warned.
    void pre() throws Exception{}
    void solve(int TC) throws Exception{
        int n = ni(), m = ni();
        int[] count = new int[n];
        for(int i = 0; i< n; i++)count[i] = ni();
        int[] offer = new int[n];
        for(int i = 0; i< m; i++){
            int d = ni(), t = ni()-1;
            offer[t] = Math.max(offer[t], d);
        }
        HashSet<Integer>[] adj = new HashSet[MX];
        for(int i = 0; i< MX; i++)adj[i] = new HashSet<>();
        for(int i = 0; i< n; i++)adj[offer[i]].add(i);
        int lo = 0, hi = MX-1;
        while(lo+1<hi){
            int mid = lo+(hi-lo)/2;
            if(check(count, adj, mid))hi = mid;
            else lo = mid;
        }
        if(check(count, adj,lo))hi = lo;
        pn(hi);
    }
    boolean check(int[] count, HashSet<Integer>[] offer, int days){
        long coin = 0;
        long rem = 0;
        for(int i:offer[0])rem+=2*count[i];
        for(int i = days+1; i< MX; i++)for(int x:offer[i])rem+=2*count[x];
        for(int cur = 1; cur<= days; cur++){
            coin+=1;
            for(int i:offer[cur]){
                long mn = Math.min(coin, count[i]);
                rem+=2*(count[i]-mn);
                coin-=mn;
            }
        }
        if(coin>=rem)return true;
        return false;
    }
    //SOLUTION END
    void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
    long mod = (long)998244353, IINF = (long)1e18;
    final int INF = (int)1e9, MX = (int)3e5+1;
    DecimalFormat df = new DecimalFormat("0.00000000000");
    double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8;
    static boolean multipleTC = false, memory = false;
    FastReader in;PrintWriter out;
    void run() throws Exception{
        in = new FastReader();
        out = new PrintWriter(System.out);
        //Solution Credits: Taranpreet Singh
        int T = (multipleTC)?ni():1;
        pre();for(int t = 1; t<= T; t++)solve(t);
        out.flush();
        out.close();
    }
    public static void main(String[] args) throws Exception{
        if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
        else new Main().run();
    }
    long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
    int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
    int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
    void p(Object o){out.print(o);}
    void pn(Object o){out.println(o);}
    void pni(Object o){out.println(o);out.flush();}
    String n()throws Exception{return in.next();}
    String nln()throws Exception{return in.nextLine();}
    int ni()throws Exception{return Integer.parseInt(in.next());}
    long nl()throws Exception{return Long.parseLong(in.next());}
    double nd()throws Exception{return Double.parseDouble(in.next());}

    class FastReader{
        BufferedReader br;
        StringTokenizer st;
        public FastReader(){
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public FastReader(String s) throws Exception{
            br = new BufferedReader(new FileReader(s));
        }

        String next() throws Exception{
            while (st == null || !st.hasMoreElements()){
                try{
                    st = new StringTokenizer(br.readLine());
                }catch (IOException  e){
                    throw new Exception(e.toString());
                }
            }
            return st.nextToken();
        }

        String nextLine() throws Exception{
            String str = "";
            try{
                str = br.readLine();
            }catch (IOException e){
                throw new Exception(e.toString());
            }
            return str;
        }
    }
}

import java.util.*;
import java.io.*;
import java.text.*;
public class Main{
    //SOLUTION BEGIN
    //This code is not meant for understanding, you have been warned.
    void pre() throws Exception{}
    void solve(int TC) throws Exception{
        int n = ni(), m = ni();
        long[] count = new long[n];
        for(int i = 0; i< n; i++)count[i] = ni();
        int[] offer = new int[n];
        for(int i = 0; i< m; i++){
            int d = ni(), t = ni()-1;
            offer[t] = Math.max(offer[t], d);
        }
        int[] cnt = new int[MX];
        for(int i = 0; i< n; i++)cnt[offer[i]]++;
        int[][] g = new int[MX][];
        for(int i = 0; i< MX; i++)g[i] = new int[cnt[i]];
        for(int i = 0; i< n; i++)g[offer[i]][--cnt[offer[i]]] = i;

        long lo = 0, hi = MX;
        while(lo+1<hi){
            long mid = lo+(hi-lo)/2;
            if(check(count, g, mid))hi = mid;
            else lo = mid;
        }
        if(check(count,g,lo))hi = lo;
        pn(hi);
    }
    boolean check(long[] cnt, int[][] offer, long day){
        long[] count = Arrays.copyOfRange(cnt, 0, cnt.length);
        long coin = 0, rem = 0;
        for(int cur = 0; cur< MX; cur++){
            if(1<= cur && cur<=day){
                coin++;
                for(int x:offer[cur]){
                    long mn = Math.min(coin, count[x]);
                    count[x] -= mn;
                    coin-=mn;
                    rem+=count[x];
                }
            }else if(cur< MX)for(int x:offer[cur])rem+=count[x];
        }
        return coin>=rem*2;
    }
    //SOLUTION END
    void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
    long mod = (long)998244353, IINF = (long)1e18;
    final int INF = (int)1e9, MX = (int)1e6+1;
    DecimalFormat df = new DecimalFormat("0.00000000000");
    double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8;
    static boolean multipleTC = false, memory = false;
    FastReader in;PrintWriter out;
    void run() throws Exception{
        in = new FastReader();
        out = new PrintWriter(System.out);
        //Solution Credits: Taranpreet Singh
        int T = (multipleTC)?ni():1;
        pre();for(int t = 1; t<= T; t++)solve(t);
        out.flush();
        out.close();
    }
    public static void main(String[] args) throws Exception{
        if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
        else new Main().run();
    }
    long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
    int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
    int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
    void p(Object o){out.print(o);}
    void pn(Object o){out.println(o);}
    void pni(Object o){out.println(o);out.flush();}
    String n()throws Exception{return in.next();}
    String nln()throws Exception{return in.nextLine();}
    int ni()throws Exception{return Integer.parseInt(in.next());}
    long nl()throws Exception{return Long.parseLong(in.next());}
    double nd()throws Exception{return Double.parseDouble(in.next());}

    class FastReader{
        BufferedReader br;
        StringTokenizer st;
        public FastReader(){
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public FastReader(String s) throws Exception{
            br = new BufferedReader(new FileReader(s));
        }

        String next() throws Exception{
            while (st == null || !st.hasMoreElements()){
                try{
                    st = new StringTokenizer(br.readLine());
                }catch (IOException  e){
                    throw new Exception(e.toString());
                }
            }
            return st.nextToken();
        }

        String nextLine() throws Exception{
            String str = "";
            try{
                str = br.readLine();
            }catch (IOException e){
                throw new Exception(e.toString());
            }
            return str;
        }
    }
}

import java.util.*;
import java.io.*;
import java.text.*;
public class Main{
    //SOLUTION BEGIN
    //This code is not meant for understanding, you have been warned.
    void pre() throws Exception{}
    void solve(int TC) throws Exception{
        int n = ni(), m = ni();
        long[] count = new long[n];
        for(int i = 0; i< n; i++)count[i] = ni();
        int[] offer = new int[n];
        for(int i = 0; i< m; i++){
            int d = ni(), t = ni()-1;
            offer[t] = Math.max(offer[t], d);
        }
        int[] cnt = new int[MX];
        for(int i = 0; i< n; i++)cnt[offer[i]]++;
        int[][] g = new int[MX][];
        for(int i = 0; i< MX; i++)g[i] = new int[cnt[i]];
        for(int i = 0; i< n; i++)g[offer[i]][--cnt[offer[i]]] = i;

        int lo = 0, hi = MX-1;
        while(lo+1<hi){
            int mid = lo+(hi-lo)/2;
            if(check(count, g, mid))hi = mid;
            else lo = mid;
        }
        if(check(count,g,lo))hi = lo;
        pn(hi);
    }
    boolean check(long[] count, int[][] offer, int days){
        long coin = 0;
        long rem = 0;
        for(int i:offer[0])rem+=count[i];
        for(int i = days+1; i< MX; i++)for(int x:offer[i])rem+=count[x];
        for(int cur = 1; cur<= days; cur++){
            coin++;
            for(int i:offer[cur]){
                long mn = Math.min(coin, count[i]);
                rem+=(count[i]-mn);
                coin-=mn;
            }
        }
        return coin>=rem*2;
    }
    //SOLUTION END
    void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
    long mod = (long)998244353, IINF = (long)1e18;
    final int INF = (int)1e9, MX = (int)6e5+1;
    DecimalFormat df = new DecimalFormat("0.00000000000");
    double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8;
    static boolean multipleTC = false, memory = false;
    FastReader in;PrintWriter out;
    void run() throws Exception{
        in = new FastReader();
        out = new PrintWriter(System.out);
        //Solution Credits: Taranpreet Singh
        int T = (multipleTC)?ni():1;
        pre();for(int t = 1; t<= T; t++)solve(t);
        out.flush();
        out.close();
    }
    public static void main(String[] args) throws Exception{
        if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
        else new Main().run();
    }
    long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
    int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
    int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
    void p(Object o){out.print(o);}
    void pn(Object o){out.println(o);}
    void pni(Object o){out.println(o);out.flush();}
    String n()throws Exception{return in.next();}
    String nln()throws Exception{return in.nextLine();}
    int ni()throws Exception{return Integer.parseInt(in.next());}
    long nl()throws Exception{return Long.parseLong(in.next());}
    double nd()throws Exception{return Double.parseDouble(in.next());}

    class FastReader{
        BufferedReader br;
        StringTokenizer st;
        public FastReader(){
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public FastReader(String s) throws Exception{
            br = new BufferedReader(new FileReader(s));
        }

        String next() throws Exception{
            while (st == null || !st.hasMoreElements()){
                try{
                    st = new StringTokenizer(br.readLine());
                }catch (IOException  e){
                    throw new Exception(e.toString());
                }
            }
            return st.nextToken();
        }

        String nextLine() throws Exception{
            String str = "";
            try{
                str = br.readLine();
            }catch (IOException e){
                throw new Exception(e.toString());
            }
            return str;
        }
    }
}

import java.util.*;
import java.io.*;
import java.text.*;
public class Main{
    //SOLUTION BEGIN
    //This code is not meant for understanding, you have been warned.
    void pre() throws Exception{}
    void solve(int TC) throws Exception{
        int n = ni(), m = ni();
        long[] count = new long[n];
        for(int i = 0; i< n; i++)count[i] = ni();
        int[] offer = new int[n];
        for(int i = 0; i< m; i++){
            int d = ni(), t = ni()-1;
            offer[t] = Math.max(offer[t], d);
        }
        int[] cnt = new int[MX];
        for(int i = 0; i< n; i++)cnt[offer[i]]++;
        int[][] g = new int[MX][];
        for(int i = 0; i< MX; i++)g[i] = new int[cnt[i]];
        for(int i = 0; i< n; i++)g[offer[i]][--cnt[offer[i]]] = i;

        int lo = 0, hi = MX;
        while(lo+1<hi){
            int mid = lo+(hi-lo)/2;
            if(check(count, g, mid))hi = mid;
            else lo = mid;
        }
        if(check(count,g,lo))hi = lo;
        pn(hi);
    }
    boolean check(long[] cnt, int[][] offer, int day){
        long[] count = Arrays.copyOfRange(cnt, 0, cnt.length);
        long coin = 0, rem = 0;
        for(int cur = 0; cur< MX; cur++){
            if(1<= cur && cur<=day){
                coin++;
                for(int x:offer[cur]){
                    long mn = Math.min(coin, count[x]);
                    count[x] -= mn;
                    coin-=mn;
                    rem+=count[x];
                }
            }else if(cur< MX)for(int x:offer[cur])rem+=count[x];
        }
        return coin>=rem*2;
    }
    //SOLUTION END
    void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
    long mod = (long)998244353, IINF = (long)1e18;
    final int INF = (int)1e9, MX = (int)6e5+1;
    DecimalFormat df = new DecimalFormat("0.00000000000");
    double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8;
    static boolean multipleTC = false, memory = false;
    FastReader in;PrintWriter out;
    void run() throws Exception{
        in = new FastReader();
        out = new PrintWriter(System.out);
        //Solution Credits: Taranpreet Singh
        int T = (multipleTC)?ni():1;
        pre();for(int t = 1; t<= T; t++)solve(t);
        out.flush();
        out.close();
    }
    public static void main(String[] args) throws Exception{
        if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
        else new Main().run();
    }
    long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
    int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
    int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
    void p(Object o){out.print(o);}
    void pn(Object o){out.println(o);}
    void pni(Object o){out.println(o);out.flush();}
    String n()throws Exception{return in.next();}
    String nln()throws Exception{return in.nextLine();}
    int ni()throws Exception{return Integer.parseInt(in.next());}
    long nl()throws Exception{return Long.parseLong(in.next());}
    double nd()throws Exception{return Double.parseDouble(in.next());}

    class FastReader{
        BufferedReader br;
        StringTokenizer st;
        public FastReader(){
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public FastReader(String s) throws Exception{
            br = new BufferedReader(new FileReader(s));
        }

        String next() throws Exception{
            while (st == null || !st.hasMoreElements()){
                try{
                    st = new StringTokenizer(br.readLine());
                }catch (IOException  e){
                    throw new Exception(e.toString());
                }
            }
            return st.nextToken();
        }

        String nextLine() throws Exception{
            String str = "";
            try{
                str = br.readLine();
            }catch (IOException e){
                throw new Exception(e.toString());
            }
            return str;
        }
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.stream.IntStream;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in Actual solution is at the top
 *
 * @author NMouad21
 */
public class Main {

  public static void main(String[] args) {
    InputStream inputStream = System.in;
    OutputStream outputStream = System.out;
    InputReader in = new InputReader(inputStream);
    PrintWriter out = new PrintWriter(outputStream);
    F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
    solver.solve(1, in, out);
    out.close();
  }

  static class F2MicrotransactionsHardVersion {

    public void solve(int testNumber, InputReader in, PrintWriter out) {
      int n = in.nextInt();
      int m = in.nextInt();
      int[] k = in.nextIntArrayOneBased(n);
      final int sum = IntStream.of(k).sum();
      final int maxDay = (int) 2e5;

      ArrayList<Integer>[] s = (ArrayList<Integer>[]) new ArrayList[maxDay + 1];
      for (int i = 0; i < s.length; i++) {
        s[i] = new ArrayList<>();
      }
      for (int i = 0; i < m; i++) {
        int d = in.nextInt();
        int t = in.nextInt();
        s[d].add(t);
      }

      int lo = 0, hi = (int) 5e5, ans = hi;
      while (lo <= hi) {
        int mid = (lo + hi) / 2;
        if (sum * 2 - saved(s, Arrays.copyOf(k, k.length), Math.min(mid + 1, s.length), n) <= mid) {
          hi = mid - 1;
          ans = mid;
        } else {
          lo = mid + 1;
        }
      }

      out.println(ans);
    }

    private int saved(ArrayList<Integer>[] s, int[] k, int length, int n) {
      int[] lastSale = new int[n + 1];
      for (int i = 1; i < length; i++) {
        for (int type : s[i]) {
          lastSale[type] = i;
        }
      }

      for (int i = 1; i < length; i++) {
        final int day = i;
        s[i].sort((a, b) ->
            lastSale[a] == day ? -1 : (lastSale[b] == day ? 1 : Integer.compare(k[a], k[b])));
      }

      int saved = 0, has = 0;
      for (int i = 1; i < length; i++) {
        ++has;
        for (int type : s[i]) {
          int win = Math.min(has, k[type]);
          saved += win;
          k[type] -= win;
          has -= win;
        }
      }

      return saved;
    }

  }

  static class InputReader {

    private InputStream stream;
    private static final int DEFAULT_BUFFER_SIZE = 1 << 16;
    private static final int EOF = -1;
    private byte[] buf = new byte[DEFAULT_BUFFER_SIZE];
    private int curChar;
    private int numChars;

    public InputReader(InputStream stream) {
      this.stream = stream;
    }

    public int read() {
      if (this.numChars == EOF) {
        throw new UnknownError();
      } else {
        if (this.curChar >= this.numChars) {
          this.curChar = 0;

          try {
            this.numChars = this.stream.read(this.buf);
          } catch (IOException ex) {
            throw new InputMismatchException();
          }

          if (this.numChars <= 0) {
            return EOF;
          }
        }

        return this.buf[this.curChar++];
      }
    }

    public int nextInt() {
      int c;
      for (c = this.read(); isSpaceChar(c); c = this.read()) {
      }

      byte sgn = 1;
      if (c == 45) {
        sgn = -1;
        c = this.read();
      }

      int res = 0;

      while (c >= 48 && c <= 57) {
        res *= 10;
        res += c - 48;
        c = this.read();
        if (isSpaceChar(c)) {
          return res * sgn;
        }
      }

      throw new InputMismatchException();
    }

    public static boolean isSpaceChar(int c) {
      return c == 32 || c == 10 || c == 13 || c == 9 || c == EOF;
    }

    public int[] nextIntArrayOneBased(int n) {
      int[] ret = new int[n + 1];
      for (int i = 1; i <= n; i++) {
        ret[i] = nextInt();
      }
      return ret;
    }

  }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author KharYusuf
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastReader in = new FastReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
        solver.solve(1, in, out);
        out.close();
    }

    static class F2MicrotransactionsHardVersion {
        public void solve(int testNumber, FastReader s, PrintWriter w) {
            int n = s.nextInt(), m = s.nextInt(), MX = (int) 2e5;
            int[] re = new int[n], last = new int[n];
            long sum = 0;
            ArrayList<Integer>[] offers = new ArrayList[MX + 1];
            for (int i = 0; i <= MX; i++) offers[i] = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                re[i] = s.nextInt();
                sum += re[i];
            }
            while (m-- > 0) {
                int x = s.nextInt(), i = s.nextInt() - 1;
                offers[x].add(i);
                last[i] = Math.max(last[i], x);
            }
            long l = 1, r = sum << 1;
            while (l <= r) {
                int[] req = re.clone();
                long mid = l + r >> 1, cur = sum;
                int has = 0;
                for (int i = 1; i <= Math.min(MX, mid); i++) {
                    has++;
                    for (int j : offers[i])
                        if (req[j] > 0 && last[j] == i) {
                            int take = Math.min(has, req[j]);
                            req[j] -= take;
                            has -= take;
                            cur -= take;
                        }
                    for (int j : offers[i])
                        if (req[j] > 0) {
                            int take = Math.min(has, req[j]);
                            req[j] -= take;
                            has -= take;
                            cur -= take;
                        }
                }
                has += Math.max(0, mid - MX);
                if (cur * 2 <= has) r = mid - 1;
                else l = mid + 1;
            }
            w.println(++r);
        }

    }

    static class FastReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private FastReader.SpaceCharFilter filter;

        public FastReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {

            if (numChars == -1)
                throw new InputMismatchException();

            if (curChar >= numChars) {

                curChar = 0;

                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }

                if (numChars <= 0)
                    return -1;
            }

            return buf[curChar++];
        }

        public int nextInt() {

            int c = read();

            while (isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();

                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public boolean isSpaceChar(int c) {

            if (filter != null)
                return filter.isSpaceChar(c);

            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author KharYusuf
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastReader in = new FastReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
        solver.solve(1, in, out);
        out.close();
    }

    static class F2MicrotransactionsHardVersion {
        public void solve(int testNumber, FastReader s, PrintWriter w) {
            int n = s.nextInt(), m = s.nextInt(), MX = (int) 2e5;
            int[] re = new int[n], last = new int[n];
            long sum = 0;
            ArrayList<Integer>[] offers = new ArrayList[MX + 1];
            for (int i = 0; i <= MX; i++) offers[i] = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                re[i] = s.nextInt();
                sum += re[i];
            }
            while (m-- > 0) {
                int x = s.nextInt(), i = s.nextInt() - 1;
                offers[x].add(i);
                last[i] = x;
            }
            long l = 1, r = sum << 1;
            while (l <= r) {
                int[] req = re.clone();
                long mid = l + r >> 1, cur = sum;
                int has = 0;
                for (int i = 1; i <= Math.min(MX, mid); i++) {
                    has++;
                    for (int j : offers[i])
                        if (req[j] > 0 && last[j] == i) {
                            int take = Math.min(has, req[j]);
                            req[j] -= take;
                            has -= take;
                            cur -= take;
                        }
                    for (int j : offers[i])
                        if (req[j] > 0) {
                            int take = Math.min(has, req[j]);
                            req[j] -= take;
                            has -= take;
                            cur -= take;
                        }
                }
                if (Math.min(MX, mid) + Math.max(0, 2 * cur - has) <= mid) r = mid - 1;
                else l = mid + 1;
            }
            w.println(++r);
        }

    }

    static class FastReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private FastReader.SpaceCharFilter filter;

        public FastReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {

            if (numChars == -1)
                throw new InputMismatchException();

            if (curChar >= numChars) {

                curChar = 0;

                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }

                if (numChars <= 0)
                    return -1;
            }

            return buf[curChar++];
        }

        public int nextInt() {

            int c = read();

            while (isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();

                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public boolean isSpaceChar(int c) {

            if (filter != null)
                return filter.isSpaceChar(c);

            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author KharYusuf
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastReader in = new FastReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
        solver.solve(1, in, out);
        out.close();
    }

    static class F2MicrotransactionsHardVersion {
        public void solve(int testNumber, FastReader s, PrintWriter w) {
            int n = s.nextInt(), m = s.nextInt(), MX = (int) 2e5;
            int[] re = new int[n];
            long sum = 0;
            ArrayList<Integer>[] offers = new ArrayList[MX + 1];
            for (int i = 0; i <= MX; i++) offers[i] = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                re[i] = s.nextInt();
                sum += re[i];
            }
            while (m-- > 0) offers[s.nextInt()].add(s.nextInt() - 1);
            long l = 1, r = sum << 1;
            while (l <= r) {
                int[] req = re.clone();
                long mid = l + r >> 1, cur = sum;
                int has = 0;
                for (int i = 1; i <= Math.min(MX, mid); i++) {
                    has++;
                    for (int j : offers[i])
                        if (req[j] > 0) {
                            int take = Math.min(has, req[j]);
                            req[j] -= take;
                            has -= take;
                            cur -= take;
                        }
                }
                if (Math.min(MX, mid) + Math.max(0, 2 * cur - has) <= mid) r = mid - 1;
                else l = mid + 1;
            }
            w.println(++r);
        }

    }

    static class FastReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private FastReader.SpaceCharFilter filter;

        public FastReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {

            if (numChars == -1)
                throw new InputMismatchException();

            if (curChar >= numChars) {

                curChar = 0;

                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }

                if (numChars <= 0)
                    return -1;
            }

            return buf[curChar++];
        }

        public int nextInt() {

            int c = read();

            while (isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();

                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public boolean isSpaceChar(int c) {

            if (filter != null)
                return filter.isSpaceChar(c);

            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author KharYusuf
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastReader in = new FastReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
        solver.solve(1, in, out);
        out.close();
    }

    static class F2MicrotransactionsHardVersion {
        public void solve(int testNumber, FastReader s, PrintWriter w) {
            int n = s.nextInt(), m = s.nextInt(), MX = (int) 2e5;
            int[] re = new int[n], last = new int[n];
            long sum = 0;
            ArrayList<Integer>[] offers = new ArrayList[MX + 1];
            for (int i = 0; i <= MX; i++) offers[i] = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                re[i] = s.nextInt();
                sum += re[i];
            }
            while (m-- > 0) {
                int x = s.nextInt(), i = s.nextInt() - 1;
                offers[x].add(i);
                last[i] = Math.max(last[i], x);
            }
            long l = 1, r = sum << 1;
            while (l <= r) {
                int[] req = re.clone();
                long mid = l + r >> 1, cur = sum;
                int has = 0;
                for (int i = 1; i <= Math.min(MX, mid); i++) {
                    has++;
                    for (int j : offers[i])
                        if (req[j] > 0 && last[j] == i) {
                            int take = Math.min(has, req[j]);
                            req[j] -= take;
                            has -= take;
                            cur -= take;
                        }
                    for (int j : offers[i])
                        if (req[j] > 0) {
                            int take = Math.min(has, req[j]);
                            req[j] -= take;
                            has -= take;
                            cur -= take;
                        }
                }
                if (Math.min(MX, mid) + Math.max(0, 2 * cur - has) <= mid) r = mid - 1;
                else l = mid + 1;
            }
            w.println(++r);
        }

    }

    static class FastReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private FastReader.SpaceCharFilter filter;

        public FastReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {

            if (numChars == -1)
                throw new InputMismatchException();

            if (curChar >= numChars) {

                curChar = 0;

                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }

                if (numChars <= 0)
                    return -1;
            }

            return buf[curChar++];
        }

        public int nextInt() {

            int c = read();

            while (isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();

                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public boolean isSpaceChar(int c) {

            if (filter != null)
                return filter.isSpaceChar(c);

            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author KharYusuf
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastReader in = new FastReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        F2MicrotransactionsHardVersion solver = new F2MicrotransactionsHardVersion();
        solver.solve(1, in, out);
        out.close();
    }

    static class F2MicrotransactionsHardVersion {
        public void solve(int testNumber, FastReader s, PrintWriter w) {
            int n = s.nextInt(), m = s.nextInt(), MX = (int) 2e5;
            int[] re = new int[n], last = new int[n];
            long sum = 0;
            ArrayList<Integer>[] offers = new ArrayList[MX + 1];
            for (int i = 0; i <= MX; i++) offers[i] = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                re[i] = s.nextInt();
                sum += re[i];
            }
            while (m-- > 0) offers[s.nextInt()].add(s.nextInt() - 1);
            long l = 1, r = sum << 1;
            while (l <= r) {
                int[] req = re.clone();
                long mid = l + r >> 1, cur = sum;
                int has = 0;
                for (int i = 1; i <= Math.min(MX, mid); i++) for (int j : offers[i]) last[j] = i;
                for (int i = 1; i <= Math.min(MX, mid); i++) {
                    has++;
                    for (int j : offers[i])
                        if (req[j] > 0 && last[j] == i) {
                            int take = Math.min(has, req[j]);
                            req[j] -= take;
                            has -= take;
                            cur -= take;
                        }
                    for (int j : offers[i])
                        if (req[j] > 0) {
                            int take = Math.min(has, req[j]);
                            req[j] -= take;
                            has -= take;
                            cur -= take;
                        }
                }
                has += Math.max(0, mid - MX);
                if (cur * 2 <= has) r = mid - 1;
                else l = mid + 1;
            }
            w.println(++r);
        }

    }

    static class FastReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private FastReader.SpaceCharFilter filter;

        public FastReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {

            if (numChars == -1)
                throw new InputMismatchException();

            if (curChar >= numChars) {

                curChar = 0;

                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }

                if (numChars <= 0)
                    return -1;
            }

            return buf[curChar++];
        }

        public int nextInt() {

            int c = read();

            while (isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();

                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public boolean isSpaceChar(int c) {

            if (filter != null)
                return filter.isSpaceChar(c);

            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;

public class Main {
	private static final long MOD = 1000000007;
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve() {
		int n = ni();
		int k = ni();
		int[] a = na(n);

		int dis[][] = na(k, 2);
		Arrays.sort(dis, new Comparator<int[]>() {
			public int compare(int[] o1, int[] o2) {
				return o2[0] - o1[0];
			}
		});

//		tr(dis);
		long sum = Arrays.stream(a).asLongStream().sum() * 2;

		long l = 0;
		long r = sum * 2;
		while (l < r) {
			long m = (l + r) / 2;
			long lastDay = m;
			long deals = 0;
			int[] req = Arrays.copyOf(a, n);
			for (int i = 0; i < k; i++) {
				if (dis[i][0] < lastDay)
					lastDay = dis[i][0];
				if (lastDay > 0 && req[dis[i][1] - 1] > 0) {
					long canBuy = Math.min(lastDay, req[dis[i][1] - 1]);
					req[dis[i][1] - 1] -= canBuy;
					lastDay -= canBuy;
					deals += canBuy;
//					tr("-", i, deals, canBuy, lastDay);
				}
			}
//			tr(sum, deals, l, r, m);
			if (sum - deals > m)
				l = m + 1;
			else
				r = m;
		}

		out.println(r);
	}

	StringBuffer sb = new StringBuffer();

	void run() throws Exception {
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);
		Thread t = new Thread(null, null, "~", Runtime.getRuntime().maxMemory()) {
			@Override
			public void run() {
				long s = System.currentTimeMillis();
				solve();
				out.flush();
				if (!INPUT.isEmpty())
					tr(System.currentTimeMillis() - s + "ms");
			}
		};
		t.start();
		t.join();

		// long s = System.currentTimeMillis();
		// solve();
		// out.flush();
		// if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
	}

	public static void main(String[] args) throws Exception {
		new Main().run();
	}

	private byte[] inbuf = new byte[1024];
	public int lenbuf = 0, ptrbuf = 0;

	private int readByte() {
		if (lenbuf == -1)
			throw new InputMismatchException();
		if (ptrbuf >= lenbuf) {
			ptrbuf = 0;
			try {
				lenbuf = is.read(inbuf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (lenbuf <= 0)
				return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c) {
		return !(c >= 33 && c <= 126);
	}

	private int skip() {
		int b;
		while ((b = readByte()) != -1 && isSpaceChar(b))
			;
		return b;
	}

	private double nd() {
		return Double.parseDouble(ns());
	}

	private char nc() {
		return (char) skip();
	}

	private String ns() {
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n) {
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while (p < n && !(isSpaceChar(b))) {
			buf[p++] = (char) b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m) {
		char[][] map = new char[n][];
		for (int i = 0; i < n; i++)
			map[i] = ns(m);
		return map;
	}

	private int[] na(int n) {
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}

	private int[][] na(int n, int m) {
		int[][] a = new int[n][];
		for (int i = 0; i < n; i++)
			a[i] = na(m);
		return a;
	}

	private int ni() {
		int num = 0, b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl() {
		long num = 0;
		int b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private int max(int[] a) {
		int ret = Integer.MIN_VALUE;
		for (int i : a)
			ret = Math.max(ret, i);
		return ret;
	}

	private static void tr(Object... o) {
		System.out.println(Arrays.deepToString(o));
	}
}

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;

public class Main {
	private static final long MOD = 1000000007;
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve() {
		int n = ni();
		int k = ni();
		int[] a = na(n);

		int dis[][] = na(k, 2);
		Arrays.sort(dis, new Comparator<int[]>() {
			public int compare(int[] o1, int[] o2) {
				return o2[0] - o1[0];
			}
		});

//		tr(dis);
		long sum = Arrays.stream(a).asLongStream().sum() * 2;

		long l = 0;
		long r = sum * 2;
		while (l < r) {
			long m = (l + r) / 2;
			long lastDay = m;
			long deals = 0;
			int[] req = Arrays.copyOf(a, n);
			for (int i = 0; i < k; i++) {
				if (dis[i][0] > lastDay)
					continue;
				if (dis[i][0] < lastDay)
					lastDay = dis[i][0];
				if (lastDay > 0 && req[dis[i][1] - 1] > 0) {
					long canBuy = Math.min(lastDay, req[dis[i][1] - 1]);
					req[dis[i][1] - 1] -= canBuy;
					lastDay -= canBuy;
					deals += canBuy;
//					tr("-", i, deals, canBuy, lastDay);
				}
			}
//			tr(sum, deals, l, r, m);
			if (sum - deals > m)
				l = m + 1;
			else
				r = m;
		}

		out.println(r);
	}

	StringBuffer sb = new StringBuffer();

	void run() throws Exception {
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);
		Thread t = new Thread(null, null, "~", Runtime.getRuntime().maxMemory()) {
			@Override
			public void run() {
				long s = System.currentTimeMillis();
				solve();
				out.flush();
				if (!INPUT.isEmpty())
					tr(System.currentTimeMillis() - s + "ms");
			}
		};
		t.start();
		t.join();

		// long s = System.currentTimeMillis();
		// solve();
		// out.flush();
		// if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
	}

	public static void main(String[] args) throws Exception {
		new Main().run();
	}

	private byte[] inbuf = new byte[1024];
	public int lenbuf = 0, ptrbuf = 0;

	private int readByte() {
		if (lenbuf == -1)
			throw new InputMismatchException();
		if (ptrbuf >= lenbuf) {
			ptrbuf = 0;
			try {
				lenbuf = is.read(inbuf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (lenbuf <= 0)
				return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c) {
		return !(c >= 33 && c <= 126);
	}

	private int skip() {
		int b;
		while ((b = readByte()) != -1 && isSpaceChar(b))
			;
		return b;
	}

	private double nd() {
		return Double.parseDouble(ns());
	}

	private char nc() {
		return (char) skip();
	}

	private String ns() {
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n) {
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while (p < n && !(isSpaceChar(b))) {
			buf[p++] = (char) b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m) {
		char[][] map = new char[n][];
		for (int i = 0; i < n; i++)
			map[i] = ns(m);
		return map;
	}

	private int[] na(int n) {
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}

	private int[][] na(int n, int m) {
		int[][] a = new int[n][];
		for (int i = 0; i < n; i++)
			a[i] = na(m);
		return a;
	}

	private int ni() {
		int num = 0, b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl() {
		long num = 0;
		int b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private int max(int[] a) {
		int ret = Integer.MIN_VALUE;
		for (int i : a)
			ret = Math.max(ret, i);
		return ret;
	}

	private static void tr(Object... o) {
		System.out.println(Arrays.deepToString(o));
	}
}

import java.io.*;
import java.util.*;
import java.math.*;

public class F{
  final int mod = 1000000007;
  final int maxn = (int)2e5;
  final double eps = 1e-9;

  void main(){
    // freopen("in");
    int n = nextInt();
    int m = nextInt();
    int[] k = new int[n];
    int sum = 0;
    for(int i = 0; i < n; ++i){
      k[i] = nextInt();
      sum += k[i];
    }
    int[] offer = new int[n];
    for(int i = 0; i < m; ++i){
      int d = nextInt();
      int t = nextInt();
      offer[t - 1] = Math.max(offer[t - 1], d);
    }
    List<Integer>[] sale = new ArrayList[2 * maxn + 1];
    for(int i = 0; i < sale.length; ++i){
      sale[i] = new ArrayList<Integer>();
    }
    for(int i = 0; i < n; ++i){
      sale[offer[i]].add(i);
    }
    int i = 1, j = 2 * sum;
    while(i < j){
      int mid = (i + j) / 2;
      int burles = 0;
      int[] buy = new int[n];
      for(int day = 1; day <= mid; ++day){
        ++burles;
        for(int l = 0; l < sale[day].size(); ++l){
          int item = sale[day].get(l);
          buy[item] = Math.min(k[item], burles);
          burles -= buy[item];
        }
      }
      for(int l = 0; l < n; ++l){
        burles -= 2 * (k[l] - buy[l]);
      }
      if(burles < 0){
        i = mid + 1;
      }
      else{
        j = mid;
      }
    }
    printf("%d\n", i);
  }

  final double pi = Math.acos(-1.0);
  final long infl = 0x3f3f3f3f3f3f3f3fl;
  final int inf = 0x3f3f3f3f;
  final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

  boolean zero(double x){ return x < eps; }

  PrintWriter out = new PrintWriter(System.out);
  BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 1 << 15);
  StringTokenizer tokens = new StringTokenizer("");

  F(){
    Locale.setDefault(Locale.US);       // imprime double com ponto
    main();
    out.close();
  }

  void freopen(String s){ try{ reader = new BufferedReader(new InputStreamReader(new FileInputStream(s)), 1 << 15); } catch(FileNotFoundException e){ throw new RuntimeException(e); } }

  int nextInt(){ return Integer.parseInt(next()); }
  long nextLong(){ return Long.parseLong(next()); }
  double nextDouble(){ return Double.parseDouble(next()); }
  String next(){ readTokens(); return tokens.nextToken(); }
  String nextLine(){ readTokens(); return tokens.nextToken("\n"); }

  void readTokens(){
    while(!tokens.hasMoreTokens())      // lê os dados, ignorando linhas vazias
      try{ tokens = new StringTokenizer(reader.readLine()); } catch(IOException e){ throw new RuntimeException(e); }
  }

  void printf(String s, Object... o){ out.printf(s, o); }
  void debug(String s, Object... o){ if(!ONLINE_JUDGE) System.err.printf((char)27 + "[91m" + s + (char)27 + "[0m", o); }

  public static void main(String[] args){ new F(); }
}

import java.io.*;
import java.util.*;
import java.math.*;

public class F{
  final int mod = 1000000007;
  final int maxn = (int)2e5;
  final double eps = 1e-9;

  void main(){
    // freopen("in");
    int n = nextInt();
    int m = nextInt();
    int[] k = new int[n];
    int sum = 0;
    for(int i = 0; i < n; ++i){
      k[i] = nextInt();
      sum += k[i];
    }
    int[] offer = new int[n];
    for(int i = 0; i < m; ++i){
      int d = nextInt();
      int t = nextInt() - 1;
      offer[t] = Math.max(offer[t], d);
    }
    List<Integer>[] sale = new ArrayList[2 * maxn + 1];
    for(int i = 0; i < sale.length; ++i){
      sale[i] = new ArrayList<Integer>();
    }
    for(int i = 0; i < n; ++i){
      sale[offer[i]].add(i);
    }
    int i = 1, j = 2 * sum;
    while(i < j){
      int mid = (i + j) / 2;
      int burles = 0;
      int[] buy = new int[n];
      for(int day = 1; day <= mid; ++day){
        ++burles;
        for(int item : sale[day]){
          buy[item] = Math.min(k[item], burles);
          burles -= buy[item];
        }
      }
      for(int item = 0; item < n; ++item){
        burles -= 2 * (k[item] - buy[item]);
      }
      if(burles < 0){
        i = mid + 1;
      }
      else{
        j = mid;
      }
    }
    printf("%d\n", i);
  }

  final double pi = Math.acos(-1.0);
  final long infl = 0x3f3f3f3f3f3f3f3fl;
  final int inf = 0x3f3f3f3f;
  final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

  boolean zero(double x){ return x < eps; }

  PrintWriter out = new PrintWriter(System.out);
  BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 1 << 15);
  StringTokenizer tokens = new StringTokenizer("");

  F(){
    Locale.setDefault(Locale.US);       // imprime double com ponto
    main();
    out.close();
  }

  void freopen(String s){ try{ reader = new BufferedReader(new InputStreamReader(new FileInputStream(s)), 1 << 15); } catch(FileNotFoundException e){ throw new RuntimeException(e); } }

  int nextInt(){ return Integer.parseInt(next()); }
  long nextLong(){ return Long.parseLong(next()); }
  double nextDouble(){ return Double.parseDouble(next()); }
  String next(){ readTokens(); return tokens.nextToken(); }
  String nextLine(){ readTokens(); return tokens.nextToken("\n"); }

  void readTokens(){
    while(!tokens.hasMoreTokens())      // lê os dados, ignorando linhas vazias
      try{ tokens = new StringTokenizer(reader.readLine()); } catch(IOException e){ throw new RuntimeException(e); }
  }

  void printf(String s, Object... o){ out.printf(s, o); }
  void debug(String s, Object... o){ if(!ONLINE_JUDGE) System.err.printf((char)27 + "[91m" + s + (char)27 + "[0m", o); }

  public static void main(String[] args){ new F(); }
}

import java.lang.*;
import java.math.*;
import java.util.*;
import java.io.*;
public class Main {
class Node {
    int d;
    int t;
    public Node(int d,int t){
        this.d=d;
        this.t=t;
    }

}
class Node2 implements Comparable<Node2>{
    int t;
    int cnt;
    public Node2(int t,int cnt){
        this.t=t;
        this.cnt=cnt;
    }
    public int compareTo(Node2 c){
        int t=Integer.compare(this.cnt,c.cnt);
        if(t!=0) return t;
        t=Integer.compare(this.t,c.t);
        return t;
    }
}
    void solve() {
        n=ni(); m=ni();
        a=new int[n+1];
        long sm=0;
        for(int i=1;i<=n;i++){
            a[i]=ni();
            sm+=a[i];
        }
        last=new int[n+1];
         p=new Node[m+1];
        int sz[]= new int[200001];
        cnt=new int[n+1];
        for(int i=1;i<=m;i++){
            p[i]=new Node(ni(),ni());

            last[p[i].t]=Math.max(last[p[i].t],p[i].d);
            cnt[p[i].t]++;
        }
        idx=new int[200001][];
        for(int i=0;i<=n;i++){
            sz[last[i]]++;
        }
        for(int i=0;i<=200000;i++) idx[i]=new int[sz[i]];
        for(int i=1;i<=n;i++){
            idx[last[i]][--sz[last[i]]]=i;
        }
        b=new int[n+1];
        long ans=0;
        long l=sm,r=2*sm;
        while(l<=r){
            long mid=(l+r)>>1;
            if(check(mid)) {
                ans=mid;
                r=mid-1;
            }else l=mid+1;
        }
        pw.println(ans);

    }
    int idx[][];
    int last[];
    int a[],b[];
    int n,m;
    int cnt[];
    Node p[];
    PriorityQueue<Node2> q=new PriorityQueue<>();
    boolean check(long TDays){
        long B=0,mn;
        for(int i=1;i<=n;i++) b[i]=a[i];

        for(int day=1;day<=(int)Math.min(TDays,200000);day++){
            B++;
            for(int t : idx[day]){
                mn=Math.min(b[t],B);
                B-=mn; b[t]-=mn;
            }

        }
        long total=0;
        for(int i=1;i<=n;i++) total+=b[i];
        B+=TDays-Math.min(TDays,200000);
        return total*2<=B;

    }

    long M =(long)1e9+7;
    InputStream is;
    PrintWriter pw;
    String INPUT = "";

    void run() throws Exception {
        is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        pw = new PrintWriter(System.out);
        long s = System.currentTimeMillis();
        solve();
        pw.flush();
        if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms");

    }

    public static void main(String[] args) throws Exception {
        new Main().run();
    }

    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;

    private int readByte() {
        if (lenbuf == -1) throw new InputMismatchException();
        if (ptrbuf >= lenbuf) {
            ptrbuf = 0;
            try {
                lenbuf = is.read(inbuf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (lenbuf <= 0) return -1;
        }
        return inbuf[ptrbuf++];
    }

    private boolean isSpaceChar(int c) {
        return !(c >= 33 && c <= 126);
    }

    private int skip() {
        int b;
        while ((b = readByte()) != -1 && isSpaceChar(b)) ;
        return b;
    }

    private double nd() {
        return Double.parseDouble(ns());
    }

    private char nc() {
        return (char) skip();
    }

    private String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n) {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while (p < n && !(isSpaceChar(b))) {
            buf[p++] = (char) b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private char[][] nm(int n, int m) {
        char[][] map = new char[n][];
        for (int i = 0; i < n; i++) map[i] = ns(m);
        return map;
    }

    private int[] na(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = ni();
        return a;
    }

    private int ni() {
        int num = 0, b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl() {
        long num = 0;
        int b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private boolean oj = System.getProperty("ONLINE_JUDGE") != null;

    private void tr(Object... o) {
        if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
    }

}

import java.lang.*;
import java.math.*;
import java.util.*;
import java.io.*;
public class Main {
class Node {
    int d;
    int t;
    public Node(int d,int t){
        this.d=d;
        this.t=t;
    }

}
class Node2 implements Comparable<Node2>{
    int t;
    int cnt;
    public Node2(int t,int cnt){
        this.t=t;
        this.cnt=cnt;
    }
    public int compareTo(Node2 c){
        int t=Integer.compare(this.cnt,c.cnt);
        if(t!=0) return t;
        t=Integer.compare(this.t,c.t);
        return t;
    }
}
    void solve() {
        n=ni(); m=ni();
        a=new int[n+1];
        long sm=0;
        for(int i=1;i<=n;i++){
            a[i]=ni();
            sm+=a[i];
        }
        last=new int[n+1];
         p=new Node[m+1];
        int sz[]= new int[200001];
        cnt=new int[n+1];
        for(int i=1;i<=m;i++){
            p[i]=new Node(ni(),ni());
            sz[p[i].d]++;
            last[p[i].t]=Math.max(last[p[i].t],p[i].d);
            cnt[p[i].t]++;
        }
        idx=new int[200001][];
        for(int i=1;i<=200000;i++) idx[i]=new int[sz[i]];
        for(int i=1;i<=m;i++){
            idx[p[i].d][--sz[p[i].d]]=p[i].t;
        }
        b=new int[n+1];
        long ans=0;
        long l=sm,r=2*sm;
        while(l<=r){
            long mid=(l+r)>>1;
            if(check(mid)) {
                ans=mid;
                r=mid-1;
            }else l=mid+1;
        }
        pw.println(ans);

    }
    int idx[][];
    int last[];
    int a[],b[];
    int n,m;
    int cnt[];
    Node p[];
    PriorityQueue<Node2> q=new PriorityQueue<>();
    boolean check(long TDays){
        long B=0;
        for(int i=1;i<=n;i++) b[i]=a[i];
        Arrays.fill(cnt,0);
        for(int i=1;i<=m;i++){
            cnt[p[i].t]++;
        }

        for(int day=1;day<=(int)Math.min(TDays,200000);day++){
            B++;
            q.clear();
            for(int t : idx[day]) {
                q.offer(new Node2(t,cnt[t]));
            }
            while(!q.isEmpty() && B>0){
                Node2 nd=q.poll();
                while(B>0 && b[nd.t]>0){
                    b[nd.t]--;
                    B--;
                }
            }
            for(int t : idx[day]) cnt[t]--;
        }
        long total=0;
        for(int i=1;i<=n;i++) total+=b[i];
        B+=TDays-Math.min(TDays,200000);
        return total*2<=B;

    }

    long M =(long)1e9+7;
    InputStream is;
    PrintWriter pw;
    String INPUT = "";

    void run() throws Exception {
        is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        pw = new PrintWriter(System.out);
        long s = System.currentTimeMillis();
        solve();
        pw.flush();
        if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms");

    }

    public static void main(String[] args) throws Exception {
        new Main().run();
    }

    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;

    private int readByte() {
        if (lenbuf == -1) throw new InputMismatchException();
        if (ptrbuf >= lenbuf) {
            ptrbuf = 0;
            try {
                lenbuf = is.read(inbuf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (lenbuf <= 0) return -1;
        }
        return inbuf[ptrbuf++];
    }

    private boolean isSpaceChar(int c) {
        return !(c >= 33 && c <= 126);
    }

    private int skip() {
        int b;
        while ((b = readByte()) != -1 && isSpaceChar(b)) ;
        return b;
    }

    private double nd() {
        return Double.parseDouble(ns());
    }

    private char nc() {
        return (char) skip();
    }

    private String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n) {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while (p < n && !(isSpaceChar(b))) {
            buf[p++] = (char) b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private char[][] nm(int n, int m) {
        char[][] map = new char[n][];
        for (int i = 0; i < n; i++) map[i] = ns(m);
        return map;
    }

    private int[] na(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = ni();
        return a;
    }

    private int ni() {
        int num = 0, b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl() {
        long num = 0;
        int b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private boolean oj = System.getProperty("ONLINE_JUDGE") != null;

    private void tr(Object... o) {
        if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
    }

}