121. Best Time to Buy and Sell Stock

price[i] ๋Š” i ๋ฒˆ์งธ ๋‚ ์— ์ฃผ์–ด์ง„ ์ฃผ์‹์˜ ๊ฐ€๊ฒฉ์„ ๋‚˜ํƒ€๋‚ธ๋‹ค.

์ด์ต์„ ์ตœ๋Œ€ํ™”ํ•  ์ˆ˜ ์žˆ๋Š” ๋งค์ˆ˜ ์‹œ์ ๊ณผ ๋งค๋„ ์‹œ์ ์„ ๊ตฌํ•ด
์ตœ๋Œ€ ์ด์ต์„ ๋ฐ˜ํ™˜ํ•˜๋„๋ก ์ž‘์„ฑํ•˜๋ผ.

์ด์ต์„ ์–ป์„ ์ˆ˜ ์—†๋‹ค๋ฉด 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 <= 10^5
    0 <= prices[i] <= 10^4

Solution

class Solution {
    func maxProfit(_ prices: [Int]) -> Int {
        if prices.isEmpty {
            return 0
        }
        
        var buyIndex = prices[0]
        var profit = 0
        
        for price in prices {
            if price < buyIndex {
                buyIndex = price
            } else if (price - buyIndex) > profit {
                profit = price - buyIndex
            }
        }
        
        return profit
    }
}

๋งค๊ฐœ๋ณ€์ˆ˜ prices ๊ฐ€ ๋น„์–ด์žˆ์„ ๊ฒฝ์šฐ 0 ์„ ๋ฆฌํ„ดํ•˜๊ณ  ์ข…๋ฃŒํ•œ๋‹ค.

๋งค์ˆ˜์‹œ์ ์˜ ๊ฐ€๊ฒฉ์„ ๋‚˜ํƒ€๋‚ด๋Š” ๋ณ€์ˆ˜ buyIndex ๋ฅผ prices[0] ์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•˜๊ณ ,
์ตœ๋Œ€ ์ด์ต์„ ์—ฐ์‚ฐํ•˜์—ฌ ๊ทธ ๊ฒฐ๊ณผ๊ฐ’์„ ๋‹ด์„ ๋ณ€์ˆ˜ profit ์„ 0 ์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•œ๋‹ค.

prices ๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ price ์™€ buyIndex ๋ฅผ ๋น„๊ตํ•˜์—ฌ ์ž‘์€ ๊ฐ’์„ ์ฐพ๋Š”๋‹ค.
์ด๋Š” ๋‚ฎ์€ ๊ฐ€๊ฒฉ์— ๊ตฌ๋งคํ•ด์•ผ ์ด์ต์„ ๋งŽ์ด ๋ณผ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

๊ทธ๋ฆฌ๊ณ  0 ์œผ๋กœ ์ดˆ๊ธฐํ™” ํ–ˆ์—ˆ๋˜ profit ๊ณผ ๋น„๊ตํ•˜์—ฌ (price - buyIndex)
์ฆ‰, ์ด์ต์—ฐ์‚ฐ์„ ํ•˜์˜€์„ ๋•Œ profit ๋ณด๋‹ค ํฌ๋‹ค๋ฉด profit ์— ๋Œ€์ž…ํ•˜์—ฌ ์ตœ๋Œ€ ์ด์ต์„ ์ฐพ๋Š”๋‹ค.


๐Ÿ“š Reference
LeetCode-121-BestTimeToBuyAndSellStock

ํƒœ๊ทธ: ,

์นดํ…Œ๊ณ ๋ฆฌ:

์—…๋ฐ์ดํŠธ: