-
프로그래머스 LV2 - 251029알고리즘 2025. 10. 29. 15:28
LV2. 구명보트

import java.util.*; class Solution { public int solution(int[] people, int limit) { int answer = 0; Integer[] boxed = Arrays.stream(people).boxed().toArray(Integer[]::new); Arrays.sort(boxed, Comparator.reverseOrder()); int passenger = 0; int cnt = 0; for (int i=0; i<people.length; i++) { if (boxed[i] != 0) { passenger += boxed[i]; boxed[i] = 0; cnt ++; if (passenger > limit) { answer ++; passenger = 0; cnt = 0; } else { for (int j=i+1; j<people.length; j++){ while (cnt <2 && passenger < limit) { passenger += boxed[j]; cnt ++; if (passenger == limit) { boxed[j] = 0; break; } else if (passenger > limit) { passenger -= boxed[j]; cnt --; } else { boxed[j] = 0; cnt++; } } } answer ++; passenger = 0; cnt = 0; } } } return answer; } }greedy 문제였는데 문제를 제대로 안 읽어서 시간이 아주아주아주 오래 걸렸다
거기에 인원수 제한 2를 마지막에 추가하려니 헷갈리고 코드 작성 다시 하자니 시간 아까워서 포기했다
class Solution { public int solution(int[] people, int limit) { int answer = 0; int n = people.length; Arrays.sort(people); int i = n - 1; int j = 0; while (i > j) { if (people[i] + people[j] <= limit) { i--; j++; } else { i--; } } return answer = (n - j); } }
LV2. 귤 고르기

import java.util.*; class Solution { public int solution(int k, int[] tangerine) { Arrays.sort(tangerine); int[] cntArr = new int[tangerine.length]; int idx = 0; cntArr[idx] = 1; for (int i = 1; i < tangerine.length; i++) { int target = tangerine[i-1]; if (target == tangerine[i]) { cntArr[idx] = cntArr[idx] + 1; } else { idx++; cntArr[idx] = 1; } } Arrays.sort(cntArr); int kCnt = 0; int answer = 0; for (int i = cntArr.length - 1; i >= 0; i--) { kCnt = kCnt + cntArr[i]; if (kCnt == k || kCnt > k) { answer++; return answer; } else { answer++; } } return answer; } }
LV2. 점프와 순간이동

728x90'알고리즘' 카테고리의 다른 글
프로그래머스 LV2 - 251104 (0) 2025.11.04 프로그래머스 LV2 - 251030 (0) 2025.10.30 프로그래머스 LV2 - 251024 (0) 2025.10.24 프로그래머스 LV2 - 251023 (0) 2025.10.23 프로그래머스 LV2 - 251022 (0) 2025.10.22