Solution with easy to understand explanation and code in CPP, Java, Python
Intuition\n Describe your first thoughts on how to solve this problem. \n- Sort people array to prioritize pairing lighter individuals first.\n- Use two pointer
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Sort people array to prioritize pairing lighter individuals first.\n- Use two pointers approach for efficient weight distribution.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Sort people array to prioritize lighter individuals first.\n2. Initialize two pointers, i and j, at both ends.\n3. Iterate until i crosses j.\n4. If sum of people[i] and people[j] <= limit:\n   - Increment i and decrement j.\n   - Increment boat count.\n5. If sum > limit:\n   - Decrement j without incrementing i.\n   - Increment boat count.\n6. Return the final boat count as the answer.\n\n# Complexity\n- Time complexity:O(n log n).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n```CPP []\nclass Solution {\npublic:\n    int numRescueBoats(std::vector<int>& people, int limit) {\n        std::sort(people.begin(), people.end());\n        int i = 0, j = people.size() - 1;\n        int ans = 0;\n        while (i <= j) {\n            if (people[i] + people[j] <= limit) {\n                i++;\n                j--;\n                ans += 1;\n            } else {\n                ans += 1;\n                j--;\n            }\n        }\n        return ans;\n    }\n};\n```\n```Java []\nclass Solution {\n    public int numRescueBoats(int[] people, int limit) {\n        Arrays.sort(people);\n        int i=0,j=people.length-1;int ans=0;\n        while(i<=j){\n            if(people[i]+people[j]<=limit){\n                i++;\n                j--;\n                ans+=1;\n            }\n            else{\n                ans+=1;\n                j--;\n            }\n        }\n        return ans;\n    }\n}\n```\n```Python []\nclass Solution:\n    def numRescueBoats(self, people: List[int], limit: int) -> int:\n        people.sort()\n        i, j = 0, len(people) - 1\n        ans = 0\n        while i <= j:\n            if people[i] + people[j] <= limit:\n                i += 1\n                j -= 1\n                ans += 1\n            else:\n                ans += 1\n                j -= 1\n        return ans\n\n```\n
['Array', 'Two Pointers', 'Greedy', 'Sorting', 'Python', 'C++', 'Java']