๐Ÿ“Œ 1. ๋ฌธ์ œ


121. Best Time to Buy and Sell Stock


์‚ฌ๊ณ  ํŒ”์•˜์„ ๋•Œ ๊ฐ€์žฅ ํฐ ์ด์ต ์ฐพ๊ธฐ


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.



โœ ํ’€์ด

1์ฐจ ์‹œ๋„

var maxProfit = function (prices) {
  let max = 0;
  for (let i = 0; i < prices.length; i++) {
    for (let j = i + 1; j < prices.length; j++) {
      if (prices[j] - prices[i] > max) {
        max = prices[j] - prices[i];
      }
    }
  }
  return max;
};


  • ๋‹จ์ˆœํžˆ ์ด์ค‘ for๋ฌธ์„ ๋Œ๋ ค์„œ max๊ฐ’์„ ์ฐพ์œผ๋ฉด ๋  ์ค„ ์•Œ์•˜๋‹ค. ๊ฒฐ๊ณผ๋Š” ๋งž์ง€๋งŒ ์‹œ๊ฐ„์ดˆ๊ณผ๋กœ ๋‹ค๋ฅธ ๋ฐฉ์‹์„ ์ƒ๊ฐํ•ด์•ผํ•œ๋‹ค.


2์ฐจ ์‹œ๋„

var maxProfit = function (prices) {
  let min = prices[0];
  let max = 0;
  for (let i = 1; i < prices.length; i++) {
    if (prices[i] < min) min = prices[i];
    else if (prices[i] - min > max) {
      max = prices[i] - min;
    }
  }
  return max;
};


  • for๋ฌธ์„ ๋‘๋ฒˆ ๋Œ๋ฆฌ์ง€ ์•Š๊ณ  for๋ฌธ์ด ํ•œ๋ฒˆ ๋Œ๋•Œ๋งˆ๋‹ค ์ตœ์†Ÿ๊ฐ’๊ณผ ์ตœ๋Œ“๊ฐ’, ๊ฒฐ๊ณผ ๊ฐ’์„ ๋ชจ๋‘ ๊ฐฑ์‹  ์‹œ์ผœ์ฃผ๋Š” ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ–ˆ๋‹ค.


๐Ÿ“Œ 2. ๋ฌธ์ œ


20. Valid Parentheses


์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ์ธ์ง€ ํŒ๋ณ„ํ•˜๊ธฐ


Input: s = โ€œ(]โ€
Output: false


Input: s = โ€œ{[]}โ€
Output: true



โœ ํ’€์ด

1์ฐจ ์‹œ๋„

var isValid = function (s) {
  let answer = true;
  let stack = [];

  for (let i = 0; i < s.length; i++) {
    if (s[i] === "(" || s[i] === "[" || s[i] === "{") {
      stack.push(s[i]);
    } else {
      if (stack.length === 0) answer = false;
      if (s[i] === ")" && stack[stack.length - 1] === "(") {
        stack.pop();
      } else if (s[i] === "]" && stack[stack.length - 1] === "[") {
        stack.pop();
      } else if (s[i] === "}" && stack[stack.length - 1] === "{") {
        stack.pop();
      } else {
        answer = false;
      }
    }
  }

  if (stack.length !== 0) answer = false;
  return answer;
};


  • stack ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค. ์—ฌ๋Š” ๊ด„ํ˜ธ์ผ ๋•Œ๋Š” ์Šคํƒ์— pushํ•˜๊ณ  ๋‹ซ๋Š” ๊ด„ํ˜ธ ์ผ๋•Œ๋Š” ์Šคํƒ์˜ ๋งˆ์ง€๋ง‰ ์š”์†Œ๊ฐ€ ๋‹ซ๋Š” ๊ด„ํ˜ธ์˜ ์ง์ธ์ง€ ํ™•์ธํ•œ ํ›„, ๋งž๋‹ค๋ฉด ๋งˆ์ง€๋ง‰ ์š”์†Œ๋Š” pop์‹œํ‚ค๋Š” ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ–ˆ๋‹ค.