본문 바로가기

코딩테스트/프로그래머스

[Level 1][C++] 예산

#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include <numeric>

using namespace std;

vector<int> sort(vector<int> arr)
{
     for (int i = 0; i < arr.size(); i++)
          for (int j = 1; j < arr.size() - i; j++)
               if (arr[i] > arr[i + j])
               {
                    int temp = arr[i];
                    arr[i] = arr[i + j];
                    arr[i + j] = temp;
               }
     return arr;
}

int solution(vector<int> d, int budget) {
     vector<int> arr1;
     vector<int> arr2;
     int average = accumulate(d.begin(), d.end(), 0)/d.size();

     for (int i = 0; i < d.size(); i++)
     {
          if (d[i] <= average)
               arr1.push_back(d[i]);
          else
               arr2.push_back(d[i]);
     }

     arr1 = sort(arr1);
     int answer = 0;

     for (int i = 0; i < arr1.size(); i++)
     {
          if (budget - arr1[i] < 0)
               break;
          budget -= arr1[i];
               answer++;
     }

     if (budget > average)
          {
               arr2 = sort(arr2);
               for (int i = 0; i < arr2.size(); i++)
               {
                    if (budget - arr2[i] < 0)
                         break;
                    budget -= arr2[i];
                    answer++;
               }
          }

     return answer;
}