PS/LeetCode

Best Time to Buy and Sell Stock

Hamp 2025. 1. 5. 14:06
반응형

문제

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

입력

1 <= prices.length <= 10^5 (주식 가격 정보들)
0 <= prices[i] <= 10^4 (주식 가격)

결과

ans: Int = 최대 이익

해석

매수 금액은 최소로하고 매도 금액은 최대로 진행

코드

class Solution {
    func maxProfit(_ prices: [Int]) -> Int {
        if prices.count <= 1 { // 1개 이하는 손익 계산 불가
            return 0 
        }
        
        var now = prices[0] // 현재 매수 금액 
        var profit: Int = 0 // 현재 이익 
        for price in prices {
            let cell = price - now // 지금 판다면 손익 
            profit = max(profit, cell) // 이익 최대 
            now = min(now, price)  // 매수 금액은 최소 
        }
        
        return profit
    }
}

 

반응형