๐Ÿ“ Coding Test Study/Algorithm Problem

[C++][Programmers][์Šคํƒ/ํ] ์ฃผ์‹๊ฐ€๊ฒฉ

ibelieveinme 2023. 6. 4. 20:15
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/42584

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr


*๋ฌธ์ œ ์„ค๋ช…

์ฃผ์‹ ๊ฐ€๊ฒฉ์ด ๋‚˜์™€์žˆ๋Š” prices ๋ฒกํ„ฐ๊ฐ€ ์ฃผ์–ด์ง€๊ณ , ๊ฐ ์ข…๋ชฉ๋“ค์ด ๋ช‡์ดˆ๊ฐ„ ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€์ง€ ์•Š์•˜๋Š”์ง€๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋œ๋‹ค.

stack/queue ๋ฌธ์ œ์— ์žˆ์–ด์„œ ๋ณธ ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ํ™œ์šฉํ•ด๋ณด๋ ค๊ณ  ํ–ˆ์ง€๋งŒ ์šฐ์„  ์–ด๋–ป๊ฒŒ ๋ฌธ์ œ๋ฅผ ํ‘ธ๋Š”์ง€๋ฅผ ์•Œ๊ธฐ ์œ„ํ•ด 2์ค‘ for๋ฌธ์œผ๋กœ ๋‹จ์ˆœํ•˜๊ฒŒ ๊ตฌํ˜„ํ–ˆ๋‹ค.

 

* ์•Œ์•„๋‘˜ ๊ฒƒ

stack์œผ๋กœ ํ‘ผ ๊ฒƒ.

#include <string>
#include <vector>
#include <stack>

using namespace std;

vector<int> solution(vector<int> prices) {
    vector<int> answer(prices.size());
    stack<int> s;
    int size = prices.size(); // ๊ณ„์† size๋ฅผ ๊ณ„์‚ฐํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค ์ƒ์ˆ˜๊ฐ’์œผ๋กœ ์ €์žฅํ•˜๋ฉด ์ „์ฒด ํ•จ์ˆ˜ ์ฒ˜๋ฆฌ ์‹œ๊ฐ„ ๊ฐ์†Œ
    
    for (int i = 0; i < size; ++i){
        while (!s.empty() && prices[s.top()] > prices[i]){ // ๊ฐ€๊ฒฉ์ด ์ค„์–ด๋“ค์—ˆ๋‹ค๋ฉด
            answer[s.top()] = i - s.top(); // ํ˜„์žฌ ์‹œ๊ฐ„ - ๋‹น์‹œ ์‹œ๊ฐ„
            s.pop();
        }
        s.push(i);
    }
    while (!s.empty()){
        answer[s.top()] = size - 1 - s.top(); // ์ข…๋ฃŒ ์‹œ๊ฐ„ - ๋‹น์‹œ ์‹œ๊ฐ„
        s.pop();
    }
    
    return answer;
}

 

* ์ฝ”๋“œ

#include <string>
#include <vector>

using namespace std;

vector<int> solution(vector<int> prices) {
    vector<int> answer;
    
    for(int i = 0; i < prices.size(); i++){
        int time = 0;
        for(int j = i+1; j < prices.size(); j++){
            time++;
            if(prices[i] > prices[j]) break;
        }
        answer.push_back(time);
    }
    
    return answer;
}

 

 

728x90