Binary Search on Answer
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time 
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(M*logM) : M=size of changeIndices\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(M)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    bool check(vector<int>&nums,int sec,vector<int>& I)\n    {\n       \n        int n=nums.size();\n        vector<int> last(n,-1);\n        for(int i=0;i<=sec;i++)\n            last[I[i]-1]=i;\n        int R=0;\n        int total=0;\n    \n        for(int i=0;i<=sec;i++)\n        {\n            int ind= I[i]-1;\n            if(last[ind]==i&&R>=nums[ind])\n            {\n                R-=nums[ind];\n                total++;\n                if(total==nums.size())\n                return true;\n            }\n            else\n            R++;\n\n        }\n        if(total==nums.size())\n        return true;\n        return false;\n\n    }\n    int fun(vector<int>& nums,vector<int>& I)\n    {\n        int low=0;\n        int high=I.size()-1;\n        int ans=-1;\n        while(low<=high)\n        {\n            int mid=(low+high)/2;\n            if(check(nums,mid,I))\n            {\n                ans=mid;\n                high=mid-1;\n            }else\n            low=mid+1;\n\n        }\n        return ans==-1?-1:ans+1;\n    }\n    int earliestSecondToMarkIndices(vector<int>& nums, vector<int>& I) {\n        return fun(nums,I);\n        \n    }\n};\n```
['C++']