728x90
Lv. 1 예산 - 실패
https://programmers.co.kr/learn/courses/30/lessons/12982
코딩테스트 연습 - 예산
S사에서는 각 부서에 필요한 물품을 지원해 주기 위해 부서별로 물품을 구매하는데 필요한 금액을 조사했습니다. 그러나, 전체 예산이 정해져 있기 때문에 모든 부서의 물품을 구매해 줄 수는
programmers.co.kr
복습 내용 : 각 배열요소가 들어갈지 안들어갈지로 따지는 방법을 구상했지만 실패.
참고한 내용 : 배열을 정렬시킨다음에 사용 -> 작은 수부터 넣는 것이 최대한 효율
틀린 풀이 : 아래와 같이 하게되면 배열의 뒷부분에 있는 큰 예산을 포함시킬 수 없음.
import java.io.*;
import java.util.*;
class Solution {
int possibleCount = 0;
int bestCount = 0;
//전체 예산
int totalBudget = 0;
int[] arrayCoop = {};
boolean[] isSelected = {};
public int solution(int[] d, int budget) {
totalBudget = budget;
arrayCoop = d;
isSelected = new boolean[d.length];
rec_func(1, 0);
int answer = bestCount;
return bestCount;
}
//k번째 고를때 지금까지의 사용 예산
public void rec_func(int k, int nowMoney){
//M개 모두 골랐거나 예산 을 초과한다면
if(k > arrayCoop.length || nowMoney > totalBudget){
if(bestCount < possibleCount){
bestCount = possibleCount;
}
}else{
for(int cand = 0; cand < arrayCoop.length; cand++){
if(isSelected[cand] == false){ //아직 고르지 않았을때만
possibleCount++;
isSelected[cand] = true;
//K번째
rec_func(k+1, nowMoney + arrayCoop[cand]);
possibleCount = 0 ;
isSelected[cand] = false;
}
}
}
}
}
Lv. 1 두 개 뽑아서 더하기 - 성공
복습할 내용 : 두개의 포인터?
import java.io.*;
import java.util.*;
class Solution {
public int[] solution(int[] numbers) {
int pointerI = 0;
ArrayList<Integer> arr = new ArrayList<Integer>();
while(pointerI < numbers.length - 1){
for(int i = pointerI + 1 ; i < numbers.length ; i++){
int num = numbers[pointerI] + numbers[i];
if(arr.contains(num) == false){
arr.add(num);
}
}
pointerI++;
}
Collections.sort(arr);
int[] result = new int[arr.size()];
for(int i = 0; i < arr.size(); i++){
result[i] = arr.get(i);
}
int[] answer = {};
return result;
}
}
728x90
'알고리즘' 카테고리의 다른 글
[Algorithm] 5월30일 알고리즘 연습 (0) | 2022.05.30 |
---|---|
[Algorithm] 5월29일 알고리즘 연습 (0) | 2022.05.29 |
[Algorithm] 5월 25일 알고리즘 연습 (0) | 2022.05.25 |
[Algorithm] 5월 23일 알고리즘 연습 (0) | 2022.05.23 |
[Algorithm] 5월 20일 알고리즘 연습 (0) | 2022.05.20 |
댓글