장난감을 가장 많이 살 수 있는 경우는 가격이 낮은 순서로 샀을 때이다.
따라서 정렬한 후, 합계를 더해가면서 금액보다 크거나 같을 때까지 비교하고 count를 증가시킨다.
C++의 경우 sort를 사용해서 정렬했고, python의 경우 sorted를 사용해서 정렬했다.
#include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
// Complete the maximumToys function below.
int maximumToys(vector<int> prices, int k) {
int Sum, c=0;
sort(prices.begin(), prices.end());
for(int i: prices){
if(Sum<=k) { Sum += i; c++; }
else break;
}
return c-1;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string nk_temp;
getline(cin, nk_temp);
vector<string> nk = split_string(nk_temp);
int n = stoi(nk[0]);
int k = stoi(nk[1]);
string prices_temp_temp;
getline(cin, prices_temp_temp);
vector<string> prices_temp = split_string(prices_temp_temp);
vector<int> prices(n);
for (int i = 0; i < n; i++) {
int prices_item = stoi(prices_temp[i]);
prices[i] = prices_item;
}
int result = maximumToys(prices, k);
fout << result << "\n";
fout.close();
return 0;
}
vector<string> split_string(string input_string) {
string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
return x == y and x == ' ';
});
input_string.erase(new_end, input_string.end());
while (input_string[input_string.length() - 1] == ' ') {
input_string.pop_back();
}
vector<string> splits;
char delimiter = ' ';
size_t i = 0;
size_t pos = input_string.find(delimiter);
while (pos != string::npos) {
splits.push_back(input_string.substr(i, pos - i));
i = pos + 1;
pos = input_string.find(delimiter, i);
}
splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
return splits;
}
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the maximumToys function below.
def maximumToys(prices, k):
s=c=0
for i in sorted(prices):
if s <= k:
s += i
c += 1
return c-1
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nk = input().split()
n = int(nk[0])
k = int(nk[1])
prices = list(map(int, input().rstrip().split()))
result = maximumToys(prices, k)
fptr.write(str(result) + '\n')
fptr.close()
[HackerRank] Alternating Characters (String Manipulation) (C++, Python) (0) | 2021.01.17 |
---|---|
[HackerRank] Strings: Making Anagrams (String Manipulation) (C++) (0) | 2021.01.17 |
[HackerRank] Sorting: Bubble Sort (Sorting) (0) | 2021.01.16 |
[HackerRank] Two Strings (python) (0) | 2021.01.14 |
[HackerRank] Hash Tables: Ransom Note (C++) (0) | 2021.01.14 |