Advertisement
atulsingh7890

Boats to Save People

Jan 13th, 2021
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. /*
  2.  
  3.   Boats to Save People
  4.  
  5.  
  6. https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/580/week-2-january-8th-january-14th/3602/
  7.  
  8. The i-th person has weight people[i], and each boat can carry a maximum weight of limit.
  9.  
  10. Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit.
  11.  
  12. Return the minimum number of boats to carry every given person.  (It is guaranteed each person can be carried by a boat.)
  13.  
  14.  
  15. Example 1:
  16.  
  17. Input: people = [1,2], limit = 3
  18. Output: 1
  19. Explanation: 1 boat (1, 2)
  20. Example 2:
  21.  
  22. Input: people = [3,2,2,1], limit = 3
  23. Output: 3
  24. Explanation: 3 boats (1, 2), (2) and (3)
  25. Example 3:
  26.  
  27. Input: people = [3,5,3,4], limit = 5
  28. Output: 4
  29. Explanation: 4 boats (3), (3), (4), (5)
  30. Note:
  31.  
  32. 1 <= people.length <= 50000
  33. 1 <= people[i] <= limit <= 30000
  34.  
  35.  
  36. */
  37. /*
  38.     each boat can carry 2 Perons atmost , so try to pair with heavy and light person
  39. */
  40. class Solution {
  41. public:
  42.     int numRescueBoats(vector<int>& people, int limit) {
  43.        
  44.         std::sort(people.begin(), people.end());
  45.        
  46.         int boats = 0;        
  47.        
  48.         int start = 0, end = people.size() - 1;
  49.         while(start <= end) {
  50.             boats++;
  51.             if(people[start] + people[end] <= limit)
  52.                 start++;
  53.             end--;            
  54.         }
  55.        
  56.         return boats;
  57.     }
  58. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement