99클럽 코테 스터디 42일차 TIL | Best Time to Buy and Sell Stock

fever·2024년 9월 1일
0

99클럽 코테 스터디

목록 보기
42/42
post-thumbnail

🖥️ 문제

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.

📝 풀이

class Solution {
    public int maxProfit(int[] prices) {
        int buy = prices[0];
        int profit = 0;
        for (int i = 1; i < prices.length; i++) {
            buy = Math.min(buy, prices[i]);
            profit = Math.max(profit, prices[i] - buy);
        }
        return profit;
    }
}

문제는 주식을 한 번 사고, 나중에 팔아서 벌 수 있는 최대의 이익을 찾는 것이다.

먼저 buy를 첫 번째 날의 주식 가격인 prices[0]으로 초기화하고, 현재까지 주식을 살 수 있는 가장 저렴한 가격을 담는다. 그리고 profit를 0으로 초기화하여, 현재까지 계산된 최대 이익을 저장한다.

다음, 두 번째 날부터 시작하여 (i = 1) 마지막 날까지 반복문을 돌린다. 이후 buy를 업데이트하면서 현재의 buy 값과 i번째 날의 가격을 비교하고 더 작은 값을 선택한다. 또한 Math.max로 현재까지의 최대 이익과 i번째 날의 가격에서 현재 최저 구매 가격을 뺀 값(prices[i] - buy) 중 더 큰 값을 선택한다.

이렇게 반복문을 수행하면 매일 주식을 팔았을 때의 최대 이익을 쉽게 계산할 수 있다.

profile
선명한 삶을 살기 위하여

0개의 댓글