Simple code with Explanation and Analysis | Binary search
\n\nApproach:\n Sort events by startTime and traverse from event with highest startTime\n While traversing If we can find an event whose startTime > endTime of 
<br>\n\n**Approach:**\n* Sort events by startTime and traverse from event with highest startTime\n* While traversing If we can find an event whose startTime > endTime of current event then it means we can take these two in our answer set and we will update the answer accordingly\nelse we can only take the current event and update the answer accordingly\n\n<br>\n\n**Will it always give optimal answer ?**\n\nYes, because we are sorting events by startTime and traversing from event with highest startTime, so we will always have the later starting event in our map and apply binary search for endTime of current event on it, \nso we will not miss any two non - overlapping events and also all the events are getting traversed so the case where taking only events is optimal will not be missed.\n\n**Example:** If we currently have [s, e, p] then in map there are events with [s + x, e\', p\'] and only those can be non - overlapping\n<br>\n\n**Time complexity:**\n\nO(n * logn) [sort] + n * (O(logn) [binary search] + O(logn) [insert in map])\n \n = O(n * logn) + n * (2 * O(logn))\n \n = O(n * logn) + 2 * O(n * logn)\n \n ~ **O(n * logn)**\n<br>\n\n**C++ Code:**\n\n\n```\nclass Solution {\npublic:\n    int maxTwoEvents(vector<vector<int>>& e) {\n        \n        int n = e.size();\n        int ans = 0, curMax = 0;\n        \n        // sort events by startTime\n        sort(begin(e), end(e));\n        \n        // mp[i] = j denotes event started at i will give profit of j\n        map<int, int> mp;\n        \n        // start traversing from event with max startTime\n        for(int i = n-1; i >= 0; i--) {\n            \n            // seach for startTime > current endTime\n            auto start = mp.upper_bound(e[i][1]);\n            \n            // current max profit possible (for one event)\n            curMax = max(curMax, e[i][2]);\n            \n            mp[e[i][0]] = curMax;\n            \n            // if there was no startTime > endTime, we will update answer by taking only current event\n            // if we found that, then we will take that event and add current event to it\n            if(start == mp.end())\n                ans = max(ans, curMax);\n            else\n                ans = max(ans, e[i][2] + start->second);\n        }\n        \n        return ans;\n    }\n};\n```\n\n<br>
['C', 'Sorting', 'Binary Tree']