#include <bits/stdc++.h>   using namespace std;   vector<int> toOrder;   map<int, set<int>> offersByDays;   map<int, set<int>> offers;   int totSum;   int bSearch(int a, int b) {     if (a == b) {       return a;     }     int curSum = totSum;     int mid = (a + b) / 2;     int money = 0;     for (int i = 0; i <= mid; i++) {       money++;       if (offersByDays.count(i) == 0) {         continue;       }       for (auto offer : offersByDays[i]) {         if (money == 0) {           break;         }         set<int>::iterator itr = offers[offer].lower_bound(mid);         if (itr != offers[offer].end() && *itr == mid) {           if (i != mid) {             continue;           }         } else {           itr = prev(itr);           if (i != *itr) {             continue;           }         }         if (money >= toOrder[offer]) {           money -= toOrder[offer];           curSum -= toOrder[offer];         } else {           curSum -= money;           money = 0;         }       }     }     if (money >= 2 * curSum) {       return bSearch(a, mid);     }     return bSearch(mid + 1, b);   }   int main() {     int n, m;     cin >> n >> m;     totSum = 0;     for (int i = 0; i < n; i++) {       int temp;       cin >> temp;       toOrder.push_back(temp);       totSum += temp;     }     for (int i = 0; i < m; i++) {       int a, b;       cin >> a >> b;       a--;       b--;       if (offersByDays.count(a) == 0) {         offersByDays.insert({a, {b}});       } else {         offersByDays[a].insert(b);       }       if (offers.count(b) == 0) {         offers.insert({b, {a}});       } else {         offers[b].insert(a);       }     }     cout << bSearch(0, int(4e5)) + 1 << endl;   }   