๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm

[Algorithm/Java][LeetCode] 121. Best Time to Buy and Sell Stock

๋ฐ˜์‘ํ˜•

[LeetCode] 121. Best Time to Buy and Sell Stock

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

๋ฌธ์ œ์ ‘๊ทผ

๊ฐ€์žฅ ์‹ธ๊ฒŒ ์‚ฌ์„œ ๊ฐ€์žฅ ๋น„์‹ธ๊ฒŒ ์ƒ€์„ ๋•Œ ์–ป๋Š” ์ด์œค์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.
๋‹ค์ด๋‚˜๋ฏน ํ”„๋กœ๊ทธ๋ž˜๋ฐ์„ ์ด์šฉํ•ด์„œ dp๋ฐฐ์—ด์— ์ง€๊ธˆ๊นŒ์ง€ ์ค‘์—์„œ ๊ฐ€์žฅ ์‹ผ ๊ฐ’์„ ์ €์žฅํ•˜๊ณ  ํ˜„์žฌ ๋‚ ์งœ์˜ ๊ฐ€๊ฒฉ prices[i]์™€ ๊ทธ ์ „๋‚ ๊นŒ์ง€ ๊ฐ€์žฅ ์‹ผ ๊ฐ€๊ฒฉ dp[i-1]์„ ๋นผ์„œ ์ด์œค์„ ๊ตฌํ•œ ๋‹ค์Œ max์™€ ๋น„๊ตํ•œ๋‹ค.
๊ทธ๋ฆฌ๊ณ  ์˜ค๋Š˜ ๊ฐ€๊ฒฉ์ด dp[i-1]๋ณด๋‹ค ์‹ธ๋‹ค๋ฉด dp[i]๋ฅผ ์˜ค๋Š˜ ๊ฐ€๊ฒฉ์œผ๋กœ ๋ฐ”๊ฟ”์ฃผ๊ณ  ์•„๋‹ˆ๋ผ๋ฉด dp[i-1]์„ ๋„ฃ์–ด์ค€๋‹ค.

Code

class Solution {
    public int maxProfit(int[] prices) {
        int max = 0;
        int[] dp = new int[prices.length]; // i๋ฒˆ์งธ ๋‚ ๊นŒ์ง€ ์ค‘ ๊ฐ€์žฅ ์‹ผ ๋ฌผ๊ฑด์˜ ๊ฐ’ ์ €์žฅ
        dp[0] = prices[0];
        for(int i =1; i<prices.length; i++){
            int profit = prices[i] - dp[i-1]; // ์ง€๊ธˆ๊นŒ์ง€ ๊ฐ€์žฅ ์‹ผ ๋ฌผ๊ฑด์˜ ๊ฐ’์„ ์ €์žฅํ•˜๊ณ  ์˜ค๋Š˜ ํŒ”์•˜์„ ๋•Œ ๋‚˜์˜ฌ์ˆ˜ ์žˆ๋Š” ์ด์œค์„ ๊ณ„์‚ฐ
            if(profit > max){
                // ์˜ค๋Š˜ ์ด์œค์ด max๋ณด๋‹ค ํฌ๋‹ค๋ฉด max๋ฅผ ์ €์žฅ
                max = profit;
            }
            dp[i] = (dp[i-1] > prices[i]) ? prices[i] : dp[i-1]; // ์˜ค๋Š˜ ๊ฐ€๊ฒฉ์ด ๋” ์ž‘๋‹ค๋ฉด ์ง€๊ธˆ๊นŒ์ง€ ์ค‘ ๊ฐ€์žฅ ๋‚ฎ์€ ๊ฐ€๊ฒฉ์ด๋ฏ€๋กœ dp[i]์— ์ €์žฅ
        }
        return max;
    }
}

์–ด๋ ค์› ๋˜ ์  / ๋ฐฐ์šด ์  / ๋Š๋‚€ ์ 

๋งŽ์ด ํ’€์–ด๋ณธ DP๋ฌธ์ œ๋ผ์„œ ์‰ฝ๊ฒŒ ์ ‘๊ทผํ•ด์„œ ํ’€์—ˆ๋˜ ๋ฌธ์ œ์ด๋‹ค. ๊ตณ๊ตณ

๋ฐ˜์‘ํ˜•