알고리즘/자료구조

[LeetCode] 121. Best Time to Buy and Sell Stock - Java

jny0 2023. 8. 24. 23:53

 

 

Best Time to Buy and Sell Stock - LeetCode

Can you solve this real interview question? Best Time to Buy and Sell Stock - You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosin

leetcode.com

 

문제

더보기

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 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:

  • 1 <= prices.length <= 105
  • 0 <= prices[i] <= 104

 

가격 배열 prices가 주어지며 여기서 prices[i]i일에 주어진 주식의 가격이다.

주식을 사는 날을 정하고 미래에 주식을 파는 날을 선택하여 수익을 극대화 하고자 할 때,

이 거래로 얻을 수 있는 최대 profit을 반환하는 문제이다.

 


 

내 풀이

 

첫 번째 풀이

class Solution {
    public int maxProfit(int[] prices) {

        int profit = 0;
        for(int i=0; i<prices.length; i++){
            for(int j=i+1; j<prices.length; j++){
                profit = Math.max(profit, prices[j] - prices[i]);
            }
        }
        return profit;

    }
}

가장 간단한 생각

이중 for문을 사용해 배열을 순회하면서 가장 큰 profit을 찾는다.

시간복잡도가 O(n^2)이고 문제에서 배열의 크기가 상당히 크기때문에 당연히 시간초과 날 거라는 생각을 했다.

역시나 시간초과로 실패했다.

 

 

두 번째 풀이

class Solution {
    public int maxProfit(int[] prices) {

       int maxProfit = 0;
       int minPrice = Integer.MAX_VALUE;

       for(int price : prices){
           if(price < minPrice){
               minPrice = price;
           }
            maxProfit = Math.max(maxProfit, price - minPrice);
       }

       return maxProfit;
    }
}

maxProfitminPrice를 각각 0과 최대 정수 값으로 초기화해준 후, 배열을 순회하면서 가장 낮은 가격인 minPrice 를 갱신한다.

동시에 최대 이익인 maxProfit 도 현재 price 에서 minPrice 를 뺀 값과 비교하여 계속 갱신해준다.

이렇게 하면 순회를 한번만 하기 때문에 시간복잡도가 O(n)으로 줄어든다.

 

  • 시간복잡도 : O(n)
  • 공간복잡도 : O(1)

 

다른사람들의 풀이를 찾아봤는데 비슷한 로직을 사용해서 푼 코드들이 대부분이었다.

최선의 시간, 공간 복잡도로 풀이에 성공해서 뿌듯하다.