(Leetcode) [Array]: Best time to buy and sell stock

Topic: Array
Difficulty: Easy


Vector์— ์ฃผ์‹ ๊ธˆ์•ก์ด ๋‚ ์งœ์ˆœ์œผ๋กœ ๋‚˜์—ด๋˜์–ด ์žˆ๋‹ค.
๊ฑฐ๋ž˜๋ฅผ ํ•ด์„œ ๋‚ผ ์ˆ˜ ์žˆ๋Š” ๊ฐ€์žฅ ํฐ ์ด์ต์„ ์ฐพ๋Š” ๋ฌธ์ œ์ด๋‹ค.

By default, map is sorted in increasing order based on its key.

My first idea

  1. for loop์„ ์ด์šฉํ•ด์„œ ์ฒซ๋ฒˆ์งธ ์ˆซ์ž๋ถ€ํ„ฐ ๊ฐ ์ˆซ์ž๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋‘”๋‹ค. max๋ผ๋Š” int variable์„ ๋งŒ๋“ ๋‹ค.
  2. ๊ธฐ์ค€ ์ˆซ์ž๋ณด๋‹ค ๋’ค์— ์žˆ๋Š” ์ˆซ์ž๋“ค์ค‘์— ์ตœ๋Œ“๊ฐ’์„ ์ฐพ๋Š”๋‹ค.
  3. โ€˜์ตœ๋Œ“๊ฐ’-๊ธฐ์ค€โ€™์ด max๋ณด๋‹ค ์ž‘์œผ๋ฉด max = ์ตœ๋Œ“๊ฐ’ - ๊ธฐ์ค€.

๊ฒฐ๊ณผ: time-limit exceeded.

My second idea

  1. min_element ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด์„œ ์ œ์ผ ์ž‘์€ ์ˆซ์ž์˜ ์ธ๋ฑ์Šค๋ฅผ ์ฐพ๋Š”๋‹ค.
  2. ๊ทธ ์ธ๋ฑ์Šค ์ดํ›„์— ์ˆซ์ž๋“ค ์ค‘์—์„œ ์ œ์„ ํฐ ์ˆซ์ž๋ฅผ ์ฐพ์•„์„œ ์ด์ต์„ ์ฐพ๋Š”๋‹ค.

๋ฌธ์ œ์ : ์ด๋ ‡๊ฒŒ ์ฐพ์€ ์ด์ต์ด ํ•ญ์ƒ ์ตœ๋Œ“๊ฐ’์ด๋ผ๋Š” ๋ณด์žฅ์€ ์—†๋‹ค. ๋ฌด์กฐ๊ฑด ์ตœ์†Ÿ๊ฐ’์œผ๋กœ ์ตœ๋Œ€ ์ด์ต์„ ๋‚ด๋Š”๊ฑด ์•„๋‹ˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.
์•„๋ž˜๋Š” ์—ฃ์ง€ ์ผ€์ด์Šค์ด๋‹ค.

stock-question-edge-case.png

Solution

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int minPrice = prices[0];
        int maxProfit = 0;

        for (int i=1; i<prices.size(); i++) {
            if (minPrice > prices[i]) {
                minPrice = prices[i];
            }
            else if (maxProfit < prices[i]-minPrice) {
                maxProfit = prices[i]-minPrice;
            }
        }
        return maxProfit;
    }
};

๊ต‰์žฅํžˆ ๊ฐ„๋‹จํ•œ ๋ฌธ์ œ์˜€๋‹ค,,
loop์„ ํ•œ ๋ฒˆ๋งŒ ๋Œ๊ณ ๋„ ์ฐพ์„ ์ˆ˜ ์žˆ์—ˆ๋‹ค.
์ผ๋‹จ 2๊ฐœ์˜ ๋ณ€์ˆ˜, minPrice์™€ maxProfit์„ ๋งŒ๋“ ๋‹ค.
loop์„ ๋Œ๋ฉด์„œ minPrice์™€ maxProfit์„ ๋™์‹œ์— ์—…๋ฐ์ดํŠธ ํ•ด์ฃผ๋ฉด ๋œ๋‹ค.
minPrice๋Š” return๋˜์ง€ ์•Š๋Š” ๊ฐ’์ด๊ธฐ ๋•Œ๋ฌธ์— ๊ทธ๋ƒฅ ๋น„๊ต ์šฉ๋„๋กœ๋งŒ ์‚ฌ์šฉ๋  ์ˆ˜ ์žˆ๋‹ค.

์•„์ง ๋‚œ ๊ฐˆ ๊ธธ์ด ๋ฉ€์—ˆ๋‹ค.

Categories:

Updated:

Leave a comment