[Programmers]_C++_Algorithm_최댓값과 최솟값

신치우·2025년 4월 12일

C++_algorithm

목록 보기
17/17

c++에는 vector에서 min, max를 구하는 함수가 따로 있지만 여기서는 MIN, MAX를 만들어서 풀었습니다.
vector에서 사용하는 함수 방법

vector<int> v;
int max = *max_element(v.begin(), v.end());
int min = *min_element(v.begin(), v.end());
#include <string>
#include <vector>
#include <sstream>

using namespace std;

#define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
#define MAX(X,Y) ((X) > (Y) ? (X) : (Y))

string solution(string s) {
    string answer = "";
    vector<int> numbers;
    
    stringstream ss(s);
    string word;
    
    while(ss>>word){
        numbers.push_back(stoi(word));
    }
    
    int m = numbers[0];
    int x = numbers[0];
    
    for(int i = 1; i<numbers.size(); i++){
        m = MIN(m, numbers[i]);
        x = MAX(x, numbers[i]);
    }
    
    answer = to_string(m) + " " + to_string(x);
    return answer;
}
profile
https://shin8037.tistory.com/

0개의 댓글