Algorithm/C++ - 프로그래머스

프로그래머스 - 예산 C++

ㅇㅇ잉 2021. 2. 20. 00:35

테스트케이스 3번에서 틀렸는데 왜지? 했더니만

첫 원소가 예산보다 컸을때를 처리해주지 않았었다.

예산을 더하다가 같으면 break, 커지면 answer-1하고 break하면 끝!

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include <algorithm>
 
using namespace std;
 
int solution(vector<int> d, int budget) {
    int answer = 0;
    int tmp=0;
    
    sort(d.begin(),d.end());
    
    for(int i=0;i<d.size();i++){
        tmp+=d[i];
        answer++;
        if(tmp==budget) break;
        if(tmp>budget) {--answer;break;}
    }
    return answer;
}
cs