[프로그래머스] 예산 (C++)

호이·2021년 11월 19일
post-thumbnail

요약

input: 부서별로 요청한 예산의 배열, 총예산
output: 총예산을 초과하지 않는 범위에서 구매 가능한 최대 부서의 수 반환

풀이

내 풀이

#include <vector>
#include <algorithm>

using namespace std;

int solution(vector<int> d, int budget) {
  int answer = 0, count = 0;
  sort(d.begin(), d.end());
  for (int n : d) {
    if ((answer + n) <= budget) {
      answer += n;
      count++;
    } else {
      break;
    }
  }
  return count;
}

int main() {
  assert(solution({1, 3, 2, 5, 4}, 9) == 3);
  assert(solution({2, 2, 3, 3}, 10) == 4);
}
  • 정렬 이후 for문으로 확인해서 더하면 간단히 풀 수 있다.
profile
매일 부활하는 개복치

0개의 댓글