Best Time to Buy and Sell Stock

Edit

Difficulty: EASY

Categories: λ°°μ—΄/λ¬Έμžμ—΄λ™μ  κ³„νšλ²• (DP)

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


Solutions

Add Solution
JAVA 2026-09-29 12:00 Edit
class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE;
        int maxProfit = 0;
        for (int price : prices) {
            if (price < minPrice) minPrice = price;
            else if (price - minPrice > maxProfit) maxProfit = price - minPrice;
        }
        return maxProfit;
    }
}
Notes:

[μžλ™ 풀이 Β· gpt-4.1-mini] 주식 가격 배열을 μˆœνšŒν•˜λ©° μ΅œμ €κ°€λ₯Ό κ°±μ‹ ν•˜κ³ , ν˜„μž¬ κ°€κ²©μ—μ„œ μ΅œμ €κ°€λ₯Ό λΊ€ 이읡을 계산해 μ΅œλŒ€ 이읡을 μ—…λ°μ΄νŠΈν•œλ‹€. ν•œ 번의 순회둜 μ΅œλŒ€ 이읡을 ꡬ할 수 μžˆλ‹€. μ‹œκ°„ O(n) Β· 곡간 O(1) 주의: μ΅œμ €κ°€ κ°±μ‹  μ‹œ μ΅œλŒ€ 이읡을 λ°”λ‘œ κ³„μ‚°ν•˜μ§€ μ•Šκ³  λ”°λ‘œ 관리해야 ν•œλ‹€.