Simple Java Solution 💡
Intuition\n\nThe problem seems to involve finding the minimum number of boats needed to rescue a group of people, given a weight limit for each boat. The idea i
# Intuition\n\nThe problem seems to involve finding the minimum number of boats needed to rescue a group of people, given a weight limit for each boat. The idea is to try to maximize the number of people in each boat without exceeding the weight limit.\n\n# Approach\n\n1. First, we sort the array of people in ascending order. This is crucial as it allows us to pair the lightest and heaviest people efficiently.\n2. We initialize two pointers, **left** and **right**, pointing to the start and end of the sorted array, respectively.\n3. We also initialize a variable **boat** to count the number of boats needed.\n4. We iterate through the array using these pointers.\n- We check if the sum of weights of people at **left** and **right** pointers is less than or equal to the limit.\n- If it is, we increment **left** (indicating that this person has been assigned to a boat).\n- Regardless of whether we can accommodate both or not, we always decrement **right** (as this person will either be in a boat or not).\n- We increment boat for each iteration, as each loop represents a boat ride.\n5. Finally, we return the total number of boats required.\n\n# Complexity\n**Time complexity**:\n\n- The time complexity is dominated by the sorting operation, which is **O(n log n)**, where n is the number of people.\n- The while loop runs in **O(n)** time since we are traversing the array once.\n- So, the overall time complexity is **O(n log n)** due to the sorting.\n\n**Space complexity**:\n\n- The space complexity is **O(1)** because we are using only a constant amount of extra space for storing variables like **left**, **right**, and **boat**. The sorting operation doesn\'t require additional space as it\'s performed in-place. Therefore, the space complexity is constant.\n# Code\n```\nclass Solution {\n    public int numRescueBoats(int[] people, int limit) {\n        Arrays.sort(people);\n        int left=0, right=people.length-1;\n        int boat = 0;\n\n        while(left <= right){\n            if(people[left] + people[right] <= limit){\n                left++;\n            }\n            right--;\n\n            boat++;\n        }\n        return boat;\n\n        \n    }\n}\n```
['Java']