-
[프로그래머스 알고리즘] while과 reduce의 합작알고리즘 2023. 6. 21. 12:07
예산
function solution(d, budget) { var answer = 0, sum = 0; d.sort((a,b) => a - b); for(let i = 0; i < d.length; i++){ answer++; sum += d[i] if(sum > budget) answer--; } return answer; }
정렬이 포인트인듯 근데 다른사람 풀이를 보니 filter를 이용한 것을 while의 조건으로 줘서 해결하는 경우도 있던데 이게 좀 신박하다 그리고 계속 변수 = 0 선언하고 로직을 짜면 좀 더 쉬워지는데 그걸 자꾸 간과하고 따른짓하다가 오래걸렸다....
function solution(d, budget) { d.sort((a, b) => a - b); while (d.reduce((a, b) => (a + b), 0) > budget) { d.pop(); } return d.length; }
합에서 제일 큰수를 빼면서 정해놓은 범위 내로 오게만드는게 신박하구만
'알고리즘' 카테고리의 다른 글
[개념] 유클리드 호제법을 통한 최대공약수 + 최소공배수 (0) 2023.11.02 [프로그래머스 알고리즘] 2중반복문 (0) 2023.06.22 [프로그래머스 알고리즘] 1~N까지 배열만들기, 제곱근의 갯수와 약수의 관계 (0) 2023.06.21 [프로그래머스 level.1] 3중반복문, 소수 판별식 (0) 2023.06.21 [프로그래머스 level.1] join(), split() (0) 2023.06.21