realforceman 2021. 12. 19. 17:55
728x90

https://programmers.co.kr/learn/courses/30/lessons/42584?language=cpp# 

 

코딩테스트 연습 - 주식가격

초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요. 제한사항 prices의 각 가격은 1 이상 10,00

programmers.co.kr

 

#include <iostream>
#include <vector>
#include <list>
#include <algorithm>

using namespace std;

int firstMin(const std::vector<int>& target, int value, int startIndex) {
    int c = 0;
    for (int i = startIndex; i < target.size(); ++i) {
        if (target[i] < value) {
            return ++c;
        }
        ++c;
    }

    return c;
}

vector<int> solution(vector<int> prices) {
    std::vector<int> answer;
    int loopIndex = 0;
    while (true) {
        const int front = prices[loopIndex++];
        if (loopIndex == prices.size()) {
            answer.push_back(0);
            break;
        }

        int idx = firstMin(prices, front, loopIndex);
        answer.push_back(idx);
    }

    return answer;
}

 

 

o(n2) 으로 해서 좋지 않은듯

 

참고로 const & 안붙여서 시간초과 떳다가 고치니 해결됐음

 

문제 포인트는 탐색하는 인덱스를 기억했다가 처음부터 재탐색 하지 않도록 하는 것

 

스택/큐 문제인데 스택 큐 이용해서 풀어봐야겠다

728x90