https://school.programmers.co.kr/learn/courses/30/lessons/42885
class Solution {
public int solution(int[] people, int limit) {
int answer = 0;
Arrays.sort(people);
Stack<Integer> st = new Stack<>();
for (int i = 0; i < people.length; i++) {
st.add(people[i]);
}
while (!st.isEmpty()) {
int sum = limit;
while (sum > 0 && !st.isEmpty()) {
if ((sum -= st.peek()) >= 0) {
st.pop();
}
}
answer++;
}
return answer;
}
}
<반례>
{30, 40, 50, 60}, 100, 2
뒤에서부터 빼주면 result = 3 이 나온다.
실제로는 (30 + 60), (40 + 50) 으로 2번만으로도 충분하다.
import java.util.Arrays;
class Solution {
public int solution(int[] people, int limit) {
int answer = 0;
Arrays.sort(people);
int start = 0;
int last = people.length - 1;
while (start < last) {
if (people[start] + people[last] <= limit) {
start++;
last--;
} else {
last--;
}
answer++;
}
if (start == last) {
answer++;
}
return answer;
}
}
import java.util.Arrays;
class Solution {
public int solution(int[] people, int limit) {
Arrays.sort(people);
int i = 0;
int j = people.length - 1;
for (; i < j; --j) {
if (people[i] + people[j] <= limit)
++i;
}
return people.length - i;
}
}