Best Time to Buy and Sell Stock
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