๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 121 - Best Time to Buy and Sell Stock (Easy)

by HandHand 2021. 3. 2.

๋ฌธ์ œ

LeetCode - 121๋ฒˆ

ํ’€์ด ๊ณผ์ •

์‹œ์„ธ๊ฐ€ ์ฃผ์–ด์ง„ ๋ฐฐ์—ด์—์„œ ์ฃผ์‹์„ ์‚ฌ๊ณ  ํŒ”์•˜์„ ๋•Œ ๊ฐ€์žฅ ํฐ ์ด์œค์„ ๋‚จ๊ธฐ๋Š” ๋ฐฉ๋ฒ•์„ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์ง๊ด€์ ์œผ๋กœ ์ฃผ์‹์ด ๊ฐ€์žฅ ๋‚ฎ์„ ๋•Œ ์‚ฌ์„œ ๊ฐ€์žฅ ๋†’์„ ๋•Œ ํŒŒ๋Š” ๊ฒƒ์ด ๊ฐ€์žฅ ํฐ ์ด์œค์„ ๋‚จ๊ธด๋‹ค๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
๋”ฐ๋ผ์„œ ๋ฐฐ์—ด์˜ ๊ฐ ์š”์†Œ๋ฅผ ์ˆœํšŒํ•˜๋ฉฐ ์ตœ์†Œ ๋น„์šฉ ๊ฐ’์„ ๊ฐฑ์‹ ํ•ด์ฃผ๋Š” ๊ฒƒ๊ณผ ๋™์‹œ์— ๊ฐ ์ƒํ’ˆ๋งˆ๋‹ค ํ˜„์žฌ ์ธ๋ฑ์Šค๊นŒ์ง€ ํƒ์ƒ‰ํ•œ
์ตœ์†Œ ๋น„์šฉ ๊ณผ์˜ ์ฐจ์ด๊ฐ’์„ ํ†ตํ•ด ์ตœ๋Œ€ ํŒ๋งค ์ˆ˜์ต ์„ O(N)์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋กœ ์–ป์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ •๋‹น์„ฑ ์ฆ๋ช…

์ตœ์†Œ ๋น„์šฉ์„ ์„ ํƒํ•˜๋Š” ์šฐ๋ฆฌ์˜ ํƒ์š• ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์€ ์ž๋ช…ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ„๋‹จํžˆ ์ฆ๋ช…ํ•˜๊ณ 
O(N) ์— ํƒ์ƒ‰์„ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์ •๋‹น์„ฑ์„ ๋”ฐ์ ธ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

์šฐ์„  ๋งค ์‹œ์„ธ๋งˆ๋‹ค ์ตœ์†Œ๋น„์šฉ์„ ๊ฐฑ์‹ ํ•œ ๊ฒฐ๊ณผ ์ตœ์ ํ•ด๋ฅผ ์ฐพ์ง€ ๋ชปํ–ˆ๋‹ค๊ณ  ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.
์ด ๊ฒฝ์šฐ ์‹ค์ œ ์ตœ์ ํ•ด(๊ฐ€์ •)์—๋Š” ์œ„ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด ์ฒ˜์Œ ์ž˜๋ชป ์„ ํƒํ•œ ๋น„์šฉ J ๋ณด๋‹ค ํฐ ์‹œ์„ธ K๊ฐ€ ์žˆ์Œ์—๋„ ์ตœ์ ํ•ด๋ฅผ ์ฐพ์•˜๋‹ค๋Š” ๋œป์ž…๋‹ˆ๋‹ค.
์—ฌ๊ธฐ์„œ K ๋Œ€์‹ ์— J ๋ฅผ ์„ ํƒํ•  ๊ฒฝ์šฐ ์ตœ๋Œ€ ์ด์œค์€ ์ปค์ง€๋ฉด ์ปค์กŒ์ง€ ์ ˆ๋Œ€ ์†ํ•ด๋ณด๋Š” ์ผ์€ ๋ฐœ์ƒํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

๊ทธ๋ ‡๋‹ค๋ฉด O(N) ์— ํƒ์ƒ‰์„ ์ˆ˜ํ–‰ํ•˜๋Š” ๊ฒƒ์ด ์˜ฌ๋ฐ”๋ฅธ ์ตœ์ ํ•ด๋ฅผ ๊ตฌํ•˜๋Š” ๊ฒƒ์„ ์–ด๋–ป๊ฒŒ ๋ณด์žฅํ•ด์ค„ ์ˆ˜ ์žˆ์„ ๊นŒ์š”?

์ด๋ฅผ ์œ„ํ•ด ํ•œ ์‹œ์  i ์—์„œ price[i] - minValue ๋ฅผ ํ†ตํ•ด ์ตœ๋Œ€ ์ด์œค์„ ๊ณ„์‚ฐํ–ˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.
์ด๋•Œ ์šฐ๋ฆฌ๊ฐ€ ํ•„์š”ํ•œ minValue ๋Š” 0 ~ i ๊นŒ์ง€์˜ ์ตœ์ € ์‹œ์„ธ ์ธ ๊ฒƒ์€ ์ž๋ช…ํ•œ ์‚ฌ์‹ค์ž…๋‹ˆ๋‹ค.
์šฐ๋ฆฌ์˜ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด ์‹œ์  i ๊นŒ์ง€ ํƒ์ƒ‰์„ ์ˆ˜ํ–‰ํ•˜๋Š” ๋™์•ˆ ๊ณ„์† ์ตœ์ € ์‹œ์„ธ๋ฅผ ๊ณ„์† ๊ฐฑ์‹ ํ•˜์˜€์œผ๋ฏ€๋กœ
์˜ฌ๋ฐ”๋ฅธ ๋‹ต์„ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ์„ ๋ณด์žฅํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function (prices) {
  let minValue = 987654321;
  let maxProfit = 0;

  for (let price of prices) {
    minValue = Math.min(minValue, price);
    maxProfit = Math.max(maxProfit, price - minValue);
  }

  return maxProfit;
};
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 22 - Generate Parentheses (Medium)  (0) 2021.03.02
LeetCode 62 - Unique Paths (Medium)  (0) 2021.03.02
LeetCode 101 - Symmetric Tree (Easy)  (0) 2021.03.02
LeetCode 876 - Middle of the Linked List (Easy)  (0) 2021.03.02
LeetCode 221 - Maximal Square (Medium)  (0) 2021.03.02

๐Ÿ’ฌ ๋Œ“๊ธ€