C++ sort by difference and explanation in details
This is how I came up with the idea that we need to sort the vector by difference. Please let me know if I am not clear enough to you.\n\n1) Supposed we have a 
This is how I came up with the idea that we need to sort the vector by difference. Please let me know if I am not clear enough to you.\n\n1) Supposed we have a huge amount of energy which is enough to finish all tasks.  There must be some energy left, and we defined it as \'res\'.  If we want to finish all the tasks with minimum initial energy, \'res\' has to be minimized.\n\n2) Let\'s think about the final step (step n).  For the last task, we need to first satisfied \'minimum\' (requirement of the last tasks) and spend \'actual\' (the energy we spend on the last tasks).  Since we want the minimum \'res\', the last tasks should be the ith one such that tasks[i][1] - tasks[i][0] is the smallest among all tasks.\n\n3) Once we found the last tasks, the energy needed for the last step (step n) is fixed.  The problem is transferred to find the minimum initial energy for the rest n-1 tasks.  We can repeat 2) for these n-1 tasks, which is to find the tasks j such that tasks[j][1] - tasks[j][0] is the smallest among these n-1 tasks.\n\n4) Repeat the process for all tasks. Thus, to find the minimum initial energy, we need to finish the tasks with a larger difference earlier than the one with a smaller difference. That\'s the reason why we need to sort the tasks vector by the difference.\n\n5) Once we sort the vector, we need to satisfied the condition for each task. There are only two conditions for tasks[k]: 1. meet the requirement of tasks[k]; 2. meet the requirement of tasks[k+1] after tasks[k] is finished.\n\nComplexity:\ntime (NlogN)\nspace (NlogN)\n\nHere is my code in c++:\n```\n    int minimumEffort(vector<vector<int>>& tasks) {\n        sort(tasks.begin(), tasks.end(), [](vector<int>& v1, vector<int>& v2) {return v1[1] + v2[0] > v1[0] + v2[1];});\n        int summ = tasks.back()[1];\n        \n        for (int i = tasks.size() - 2; i >= 0; i--){\n            summ = max(tasks[i][0] + summ, tasks[i][1]);\n        }\n        return summ;\n    }\n```
[]