코딩 테스트(JAVA)/리트코드

[문제12][LeetCode] 121. 주식을 사고팔기 가장 좋은 시점

Lea Hwang 2024. 3. 30. 01:15

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/

You are given an array prices where prices[i] is the price of a given stock on the ith day.
주어진 배열 prices에서 prices[i]는 i번째 날의 특정 주식 가격입니다.


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.

이 거래로 얻을 수 있는 최대 이익을 반환하시고 만약 이익을 얻을 수 없는 경우에는 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

 

접근 방법

시간 복잡도: O(N)

1. 임시적으로 minPrice를 prices[0]으로 설정합니다.

2. 만약 이익을 얻을 수 없는 경우에는 0을 반환해야하므로 maxProfit의 초기값을 0으로 설정합니다.

3. 만약 현재 prices[i]가 minPrice보다 작다면 minPrice를 해당 prices[i]로 업데이트합니다.

4. maxProfit보다 현재 prices[i] - minPrice가 더 크다면, 더 큰 maxProfit이 나온 것이므로 해당 값으로 갱신합니다.

 

코드 구현

class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = prices[0]; 
        int maxProfit = 0;

        for(int i=0; i<prices.length; i++){
            if(prices[i] < minPrice){
                minPrice = prices[i];
            }else if(prices[i] - minPrice > maxProfit){
                maxProfit = prices[i] - minPrice;
            }
        }
        
        return maxProfit;
    }
}