첫 번째 원소 부터 끝까지, 두 번째 원소 부터 끝까지, ... 이런 식으로 검사를 반복하기 때문에
이중 for문으로 두고 답이 나오면 break를 둬서 다음 반복으로 넘어간다.
정답 컨테이너의 마지막 원소는 무조건 0이 되기 때문에 반복문을 빠져나온 후 0을 vector에 push한다.
효율성 검사를 해보니 break 연산이 사칙연산보다 시간이 오래 걸려서 뺄 수 있는 부분은 뺐다.
#include <string>
#include <vector>
#include <iostream>
using namespace std;
vector<int> solution(vector<int> prices) {
vector<int> times;
size_t length = prices.size();
for (size_t i = 0; i < length; ++i)
{
int time = 1;
for (size_t j = i+1; j < length; ++j)
{
if (prices[i] > prices[j])
{
times.push_back(time);
break;
}
if (j == length - 1)
times.push_back(time);
time += 1;
}
}
times.push_back(0);
return times;
}
int main()
{
for (auto d : solution({ 1, 2, 3, 2, 3 }))
{
cout << d << ' ';
}
}
실행결과
4 3 1 1 0