package leetcode;

import java.util.Arrays;

/**
 * https://leetcode.com/problems/boats-to-save-people/
 */
public class Problem881 {
    public int numRescueBoats(int[] people, int limit) {
        Arrays.sort(people);
        int count = 0;
        boolean[] visited = new boolean[people.length];
        for (int i = 0; i < people.length; i++) {
            if (visited[i]) {
                continue;
            }
            int index = Arrays.binarySearch(people, i, people.length, limit - people[i]);
            if (index < 0) {
                index = -index - 1;
                if (index == visited.length) {
                    index--;
                }
            } else {
                int val = people[index];
                while (index < people.length && val == people[index]) {
                    index++;
                }
                index--;
            }
            while (i < index) {
                if (!visited[index]) {
                    if (limit - (people[i] + people[index]) >= 0) {
                        visited[index] = true;
                        break;
                    }
                }
                index--;
            }
            count++;
        }
        return count;
    }
}

@@ -196,764 +196,142 @@
     
-Arrays.sort(people);%0A        int count = 0;%0A        boolean%5B%5D visited = new boolean%5Bpeople.length%5D;%0A        for (int i = 0; i %3C people.length; i++) %7B%0A            if (visited%5Bi%5D) %7B%0A                continue;%0A            %7D%0A            int index = Arrays.binarySearch(people, i, people.length, limit - people%5Bi%5D);%0A            if (index %3C 0) %7B%0A                index = -index - 1;%0A                if (index == visited.length) %7B%0A                    index--;%0A                %7D%0A            %7D else %7B%0A                int val = people%5Bindex%5D;%0A                while (index %3C people.length && val == people%5Bindex%5D) %7B%0A                    index++;%0A                %7D%0A                index--;%0A            %7D%0A            while (i %3C index) %7B%0A                if (!visited%5Bindex%5D
+int answer = 0;%0A        Arrays.sort(people);%0A        int left = 0;%0A        int right = people.length - 1;%0A        while (left %3C= right
 ) %7B%0A
@@ -346,27 +346,10 @@
     
-  
-      if (limit -
+if
  (pe
@@ -353,17 +353,20 @@
 (people%5B
-i
+left
 %5D + peop
@@ -372,107 +372,51 @@
 ple%5B
-index%5D) %3E= 0) %7B%0A                        visited%5Bindex%5D = true;%0A                        break;%0A     
+right%5D %3C= limit) %7B%0A                left++;%0A
     
@@ -415,35 +415,32 @@
 ++;%0A            
-   
 %7D%0A              
@@ -441,70 +441,35 @@
     
-    %7D%0A                index--;%0A            %7D%0A            count
+right--;%0A            answer
 ++;%0A
@@ -497,13 +497,14 @@
 urn 
-count
+answer
 ;%0A  

Update problem 881