-
[프로그래머스] 주식가격 java c++Coding Test/programmers 2023. 1. 28. 17:26728x90
문제 설명
초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.
제한 사항
- prices의 각 가격은 1 이상 10,000 이하인 자연수입니다.
- prices의 길이는 2 이상 100,000 이하입니다.
입출력 예
prices return [1, 2, 3, 2, 3] [4, 3, 1, 1, 0] 풀이
java
import java.util.*; class Solution { public int[] solution(int[] prices) { int[] answer = new int[prices.length]; for(int i = 0; i < prices.length; i++) { for(int j = i+1; j < prices.length; j++) { answer[i]++; if(prices[i] > prices[j]) break; } } return answer; } }
c++
#include <string> #include <vector> #include <stack> using namespace std; vector<int> solution(vector<int> prices) { int len = prices.size(); vector<int> answer(len, 0); stack<int> st; for(int i = 0; i < len; i++){ while(!st.empty() && prices[st.top()] > prices[i]){ answer[st.top()] = i - st.top(); st.pop(); } st.push(i); } while(!st.empty()){ answer[st.top()] = len - st.top() -1; st.pop(); } return answer; }
다른 풀이
#include <string> #include <vector> using namespace std; vector<int> solution(vector<int> prices) { vector<int> answer; int len = prices.size(); for(int i = 0; i < len; i++){ int time = 0; for(int j = i + 1; j < len; j++){ time++; if(prices[j] < prices[i] || j == len - 1){ answer.push_back(time); break; } } } answer.push_back(0); return answer; }
다른 풀이
#include <string> #include <vector> #include <stack> using namespace std; vector<int> solution(vector<int> prices) { int len = prices.size(); vector<int> answer(len, 0); stack<pair<int,int>> st; //{index, prices[index]} for(int i = len - 1; i >= 0; i--){ while(!st.empty()){ if(st.top().second >= prices[i]){ st.pop(); } else{ break; } } if(st.empty()){ answer[i] = len - i - 1; } else{ answer[i] = st.top().first - i; } st.push(make_pair(i, prices[i])); } return answer; }
728x90'Coding Test > programmers' 카테고리의 다른 글
[프로그래머스] 둘만의 암호 c++ (0) 2023.02.11 [프로그래머스] 괄호 회전하기 c++ (0) 2023.01.30 [프로그래머스] 올바른 괄호 c++ (0) 2023.01.28 [프로그래머스] 숫자 변환하기 c++ (0) 2023.01.27 [프로그래머스] 뒤에 있는 큰 수 찾기 c++ (0) 2023.01.27