
주어진 배열 prices는 prices[i]가 i번째 날 주식의 가격이다.
주식을 한 주 사는 날과 미래의 어떤 다른 날에 주식을 팔아 최대 이익을 극대화하려고 한다.
이 거래로 얻을 수 있는 최대 이익을 반환하라. 이익을 얻을 수 없는 경우 0을 반환하라.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
Constraints:
Time Limit Exceeded 시간 초과에러로 큰 배열을 받을 경우 문제가 되어 실패했습니다. 1 <= prices.length <= 10^5을 잘 체크했어야 했는데 아쉽습니다..class Solution {
public int maxProfit(int[] prices) {
int max = 0;
for(int i = 0; i < prices.length - 1; i++){
for(int j = i+1; j < prices.length; j++){
int num = prices[j] - prices[i];
if(num > max)
max = num;
}
}
return max;
}
}
방법 1) 에서 시간초과 에러 해결을 위해 시간 복잡도를 O(n)으로 해결하기 위해 생각을 해봤습니다. min값을 prices[]배열의 첫번째 index값을 저장하고 단순 반복문을 통해 min값과 비교하며 더 작은 값을 찾으면 min에 저장하고, 큰수가 나왔을 경우 profit을 계산하여 저장합니다.profit을 계산하여 저장할 때 기본 profit의 값보다 크면 저장하도록 조건을 붙여줍니다.class Solution {
public int maxProfit(int[] prices) {
int min = prices[0];
int profit = 0;
for(int i = 1; i < prices.length; i++){
if(min > prices[i]){
min = prices[i];
continue;
}
else
profit = (prices[i] - min) > profit ? (prices[i] - min) : profit;
}
return profit;
}
}
class Solution {
public int maxProfit(int[] prices) {
int min = prices[0];
int profit = 0;
for(int i = 1; i < prices.length; i++){
if(min > prices[i])
min = prices[i];
else
profit = Math.max((prices[i] - min), profit);
}
return profit;
}
}
profit = (prices[i] - min) > profit ? (prices[i] - min) : profit;을 추가 조건문 없이 처리하기 위해 삼항연산자를 사용하였습니다. profit = Math.max((prices[i] - min), profit);로 수정하였습니다.