✅ Java | Easy Solution Explained 📝 | Beginner friendly | Beats 100% | 2pointer, Greedy
Intuition\nImmediate thought that comes to mind is 2 pointers since we can carry atmost 2 people in the boat. However if we just try to go with that approach it
# Intuition\nImmediate thought that comes to mind is 2 pointers since we can carry atmost 2 people in the boat. However if we just try to go with that approach it is time consuming to find pair. So an ***obvious optimisation is to sort*** the people array first. This gives us *access to skinniest and heaviest person* at the same time and now two pointers is very handy.\n\nNote: Don\'t confuse yourself, each person\'s weight in the array will be less than limit itself\n\n---\n\n\n# Approach\n1) We sort the array so that we have access to even heaviest ans skinniest person at the same time\n2) Initialise start=0 and end = people.length-1;\n3) ***Choosen loop while(start<=end)*** \'=\' case if kept so that we donot miss the person when start==end, he/she will be a solo person in that case.\n4) We know atmost 2 people can go so, if ***people[start] + people[end] <= limit*** i.e their weight is under or equal to limit both people can go and we move the both pointers and increment boat required\nweight[start] (depicts skinnest person) and weight[end] heaviest person\n5) In above case if sum of people from start and end is > limit, we choose heavier person, this is the greediness in the approach\n\n---\n\n\n# Complexity\n- Time complexity:\nO(n) as in the worst case when each person is heavy enough and needs as entire boat.\n\n---\n\n\nHope it is easy to understand.\nLet me know if there is something unclear and i can fix it.\n\nOtherwise, please upvote if you like the solution, it would be encouraging\n\n![LCUpvote.png](https://assets.leetcode.com/users/images/f1a2f2d3-133d-4704-b75a-a77df38b1f4e_1680488411.0057132.png)\n\n\n# Code\n```\nclass Solution {\n  /* Two pointer technique */\n    public int numRescueBoats(int[] people, int limit) {\n      Arrays.sort(people);\n      /* we know that atmost 2 people can go in boat.\n      So sorting is done so that we can have access to heaviest\n      and skiniest person at the same time */\n      int boat=0;\n      int start=0;\n      int end= people.length-1;\n      while(end>=start){ \n        if(people[start]+ people[end] <=limit){\n          start++;\n          end--;\n        }else{\n          /* heaviest will take the boat */\n          end--;\n        }\n        boat++;\n      }\n      return boat;\n      \n    }\n}\n```
['Two Pointers', 'Greedy', 'Java']