Easy C++ Sorting Solution | Beginner Friendly 💯✅
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires finding the minimum number of boats needed to rescue a group of pe
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires finding the minimum number of boats needed to rescue a group of people, where each boat can carry at most `limit` weight. The intuition behind the solution is to pair the heaviest person with the lightest person who can fit in the same boat. This approach ensures efficient utilization of boat capacity and minimizes the number of boats required.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Sorting:** First, we sort the people array in ascending order of their weights. This allows us to efficiently pair the heaviest and lightest persons.\n2. **Two Pointers:** We use two pointers technique. One pointer (`heavyPtr`) starts from the end of the array (representing the heaviest person) and moves towards the beginning, while the other pointer (`lightPtr`) starts from the beginning of the array (representing the lightest person) and moves towards the end.\n3. **Pairing:** For each iteration, we check if the sum of weights of the person pointed by `lightPtr` and the person pointed by `heavyPtr` is less than or equal to the `limit`. If it is, we increment `lightPtr` to move to the next lightest person. Regardless, we always increment the count of boats as we must send a boat for the heaviest person.\n4. **Termination:** We continue this process until both pointers meet or cross each other, ensuring that all people are considered for rescue.\n\n# Complexity\n- Time complexity: O(NlogN)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    int numRescueBoats(vector<int>& people, int limit) {\n        int boats = 0;\n\n      \n        sort(people.begin(), people.end()); \n      \n        int lightPtr = 0;\n        for(int heavyPtr = people.size() - 1; heavyPtr >= 0 && lightPtr <= heavyPtr; heavyPtr--) { \n            if(people[lightPtr] + people[heavyPtr] <= limit) lightPtr++;\n        \n            boats++;\n        }\n\n        return boats;\n    }\n};\n```
['Two Pointers', 'Sorting', 'C++']