[Programmers] Lv2. ์ฃผ์‹๊ฐ€๊ฒฉ | C++

2023. 6. 22. 21:31ใ†Coding Test/Programmers

๐Ÿ”—๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
 

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

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

programmers.co.kr

 

๐Ÿ‘จ‍๐Ÿ’ปํ’€์ด ๊ณผ์ •

 

๋ฌธ์ œ ์ง€๋ฌธ์˜ ์„ค๋ช…์ด ๋„ˆ๋ฌด ์ „๋‹ฌ๋ ฅ ์—†์ด ์ž‘์„ฑ๋˜์–ด ์žˆ์–ด, ๋‹ค๋ฅธ ๋ถ„์ด ์žฌํ•ด์„ํ•˜์‹  ๊ธ€์„ ์ฐธ๊ณ ํ•˜์˜€์Šต๋‹ˆ๋‹ค. ์ €๋Š” ์Šคํƒ(Stack)์„ ์ด์šฉํ•˜์—ฌ ํ’€์—ˆ์Šต๋‹ˆ๋‹ค.

  • prices์˜ ํฌ๊ธฐ๋งŒํผ answer ๋ฐฐ์—ด์— ๋ฉ”๋ชจ๋ฆฌ ๊ณต๊ฐ„์„ ํ• ๋‹นํ•ด๋‘”๋‹ค.
  • ์Šคํƒ์— ์ €์žฅ๋˜๋Š” ๋ฐ์ดํ„ฐ๋Š” <์ฃผ๊ฐ€ ๊ธˆ์•ก, ์Šคํƒ์— ์ง„์ž…ํ•œ ์‹œ์ ์˜ ์‹œ๊ฐ(์ดˆ)>์ด๋‹ค.
  • for๋ฌธ์„ ํ†ตํ•ด, 1์ดˆ๋ถ€ํ„ฐ prices ํฌ๊ธฐ๊นŒ์ง€ ์ดˆ๋ฅผ ์„ธ๋ฉฐ ์ง„ํ–‰ํ•œ๋‹ค.
    • ์Šคํƒ์ด ๋น„์—ˆ๊ฑฐ๋‚˜, ํ˜„์žฌ ์ฃผ๊ฐ€๊ฐ€ ์Šคํƒ top()์˜ ์ฃผ๊ฐ€๋ณด๋‹ค ํฌ๋‹ค๋ฉด ํ˜„์žฌ ์ฃผ๊ฐ€์™€ ์‹œ๊ฐ„์„ ์Šคํƒ์— ์‚ฝ์ž…ํ•œ๋‹ค.
    • ์œ„ ์กฐ๊ฑด์— ํ•ด๋‹นํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด, ์ฃผ๊ฐ€๊ฐ€ ๋‚ฎ์•„์ง„ ๊ฒƒ์ด๋ฏ€๋กœ ์Šคํƒ์—์„œ ํ˜„์žฌ ์ฃผ๊ฐ€๋ณด๋‹ค ํฐ ์ฃผ๊ฐ€๋“ค์„ popํ•œ๋‹ค.
      • popํ•œ ์ฃผ๊ฐ€์˜ ๊ฐ€๊ฒฉ ์œ ์ง€ ์‹œ๊ฐ„์€ (prices ํฌ๊ธฐ - popํ•œ ์ฃผ๊ฐ€์˜ ์Šคํƒ ์ง„์ž… ์‹œ์ )์ด๋‹ค.
      • popํ•œ ์ฃผ๊ฐ€์˜ ์Šคํƒ ์ง„์ž… ์‹œ์ (์ดˆ)์—์„œ 1์„ ๋นผ๋ฉด, ํ•ด๋‹น ์ฃผ๊ฐ€์˜ ์›๋ž˜ ์ธ๋ฑ์Šค์ด๋ฏ€๋กœ answer ๋ฐฐ์—ด์˜ ํ•ด๋‹น ์ธ๋ฑ์Šค ์ž๋ฆฌ์— popํ•œ ์ฃผ๊ฐ€์˜ ๊ฐ€๊ฒฉ ์œ ์ง€ ์‹œ๊ฐ„์„ ์ €์žฅํ•œ๋‹ค.
    • ์กฐ๊ฑด์— ๋”ฐ๋ผ pop์„ ๋‹ค ํ–ˆ๋‹ค๋ฉด, ํ˜„์žฌ ์ฃผ๊ฐ€์™€ ์‹œ๊ฐ„์„ ์Šคํƒ์— ์‚ฝ์ž…ํ•œ๋‹ค.
  • for๋ฌธ์„ ๋‹ค ๋Œ๊ณ , ์Šคํƒ์— ๋‚จ์€ ์ฃผ๊ฐ€๋“ค์— ๋Œ€ํ•ด ์œ„์˜ pop ๊ณผ์ •๋“ค์„ ๋ฐ˜๋ณตํ•œ๋‹ค.

 

โœ๏ธ์†Œ์Šค ์ฝ”๋“œ ๋ฐ ๊ฒฐ๊ณผ

#include <vector>
#include <stack>
using namespace std;

vector<int> solution(vector<int> prices) {
    vector<int> answer(prices.size(), 0);
    stack<pair<int, int>> priceStack;    // <์ฃผ๊ฐ€, ์Šคํƒ ์ง„์ž… ์‹œ๊ฐ>
    
    for (int second = 1; second <= prices.size(); second++) {
        int index = second - 1;

        if (priceStack.empty() or priceStack.top().first < prices[index]) {
            priceStack.emplace(prices[index], second);
            continue;
        }

        while (!priceStack.empty()) {
            pair<int, int> top = priceStack.top();
            
            if (top.first <= prices[index])
                break;
            
            int holdingTime = second - top.second;
            int targetIdx = top.second - 1;
            answer[targetIdx] = holdingTime;
            priceStack.pop();
        }

        priceStack.emplace(prices[index], second);
    }

    while (!priceStack.empty()) {
        int holdingTime = prices.size() - priceStack.top().second;
        int targetIdx = priceStack.top().second - 1;
        answer[targetIdx] = holdingTime;
        priceStack.pop();
    }
    
    return answer;
}

 

 

728x90
๋ฐ˜์‘ํ˜•