✅Easy✨||C++|| Beats 100% || With Explanation ||
Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind this solution is to sort the array of people\'s weights and then u
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this solution is to sort the array of people\'s weights and then use a two-pointer approach to pair the heaviest person with the lightest person who can fit on the same boat, iterating inward until all people are paired or considered.\nWe first chech if 1st lightest(l) and heaviest(r) can fit on boat, if they can pair them and send them in a boat, else send only heaviest. Next choose lightest and heaviest left and continue pairing until all people are filled.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Sort the array of people\'s weights in ascending order.\n2. Initialize two pointers, l and r, pointing to the start and end of the sorted array respectively.\n3. Initialize a variable boats to keep track of the number of boats required.\n4. Iterate through the array using the two-pointer approach:\n.If the sum of weights at pointers l and r is less than or equal to the limit:\n     .Move both pointers inward (l += 1 and r -= 1).\n.If the sum exceeds the limit:\n  .Move only the right pointer inward (r -= 1).\n. Increment the boats count after each iteration.\n5. Return the boats count, which represents the minimum number of boats required to rescue all people.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn)\n. Sorting the array takes O(nlogn) time.\n. The two-pointer approach takes O(n) time.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n. Sorting the array in-place takes O(1) space.\n. Additional variables (l, r, boats) take O(1) space.\n# Code\n```\nclass Solution {\npublic:\n    int numRescueBoats(vector<int>& people, int limit) {\n        sort(people.begin(), people.end());\n        int boats = 0;\n        int l = 0, r = people.size() - 1;\n\n        while (l <= r) {\n            if (people[l] + people[r] <= limit) {\n                l++;\n            }\n            r--;\n            boats++;\n        }\n\n        return boats;\n    }\n};\n```
['C++']