// Easy Code with Comments - Sort and Borrow energy when necessary
\n// Easy Code with Comments - Sort and Borrow energy when necessary\n\n\n// a[1] & b[1] are minimum energies while\n// a[0] & b[0] are actual energies required
```\n// Easy Code with Comments - Sort and Borrow energy when necessary\n\n\n// a[1] & b[1] are minimum energies while\n// a[0] & b[0] are actual energies required.\n// Sort the array in the descending order of (minimum - actual).\n// (minimum - actual) is the amount of energy that remains after \n// finishing a task. So we should try to accumulate as much energy\n// as possible in the beginning to complete the tasks coming up\n// ahead. Hence, sort the array in descending order based on the \n// amount of energy that will be remaining.\nbool comparator(vector<int> &a, vector<int>&b) {\n    return ((a[1]-a[0] > b[1]-b[0]));\n}\n// Example: [[1, 10], [1, 5], [1,20]] --> [[1, 20], [1, 10], [1, 5]]\n\n\nclass Solution {\npublic:\n    int minimumEffort(vector<vector<int>>& tasks) {\n        int answer = 0;\n        int n = tasks.size();\n        sort(tasks.begin(), tasks.end(), comparator); // custom sort, see the comment above.\n        int energy = 0; // assume initial energy is 0 and we will borrow whenever necessary.\n        for (int i=0; i<n; i++) {\n            if (energy < tasks[i][1]) { // if sufficient energy is not available,\n                int borrow = tasks[i][1]-energy; // borrow some energy.\n                answer += borrow;\n                energy += borrow; // energy increased because of borrowing.\n            }\n            energy = energy - tasks[i][0]; // now spend the energy for the task.\n        }\n        return answer; // total borrowed energy.\n    }\n};\n```
[]