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

LeetCode 11 - Container With Most Water (Medium)

by HandHand 2021. 3. 4.

๋ฌธ์ œ

LeetCode - 11๋ฒˆ

ํ’€์ด ๊ณผ์ •

๋‘ ๋ง‰๋Œ€๊ธฐ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๊ฐ€์žฅ ๋งŽ์€ ๋ฌผ์„ ๋‹ด์„ ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์„ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์™„์ „ ํƒ์ƒ‰ ์œผ๋กœ ์ ‘๊ทผํ•  ๊ฒฝ์šฐ O(N^2) ์— ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์ง€๋งŒ ํˆฌ ํฌ์ธํ„ฐ ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด O(N) ์— ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

๋‘ ๋ง‰๋Œ€๊ฐ€ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์กด์žฌํ•œ๋‹ค๊ณ  ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

ํŽธ์˜์ƒ 2, 1, 4 ํฌ๊ธฐ์˜ ๋ง‰๋Œ€๋ฅผ ๊ฐ๊ฐ ๋‹ค๋ฅธ ์œ„์น˜์— ๊ทธ๋ ธ์ง€๋งŒ
์‚ฌ์‹ค์€ ๊ฐ€์žฅ ์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ ๋ง‰๋Œ€ ์ค‘๊ฐ„์˜ ์–ด๋Š ํŠน์ • ์œ„์น˜ X ์— ์œ„์น˜ํ•  ์ˆ˜ ์žˆ๋Š” ๋ง‰๋Œ€์˜ 3 ์ข…๋ฅ˜๋ฅผ ๋‚˜ํƒ€๋‚ธ ๊ฒƒ์ž…๋‹ˆ๋‹ค.

์œ„์™€ ๊ฐ™์ด ๊ฐ€์žฅ ์™ผ์ชฝ์— ์œ„์น˜ํ•œ ๋ง‰๋Œ€๋ฅผ L ๊ทธ ๋ฐ˜๋Œ€๋ฅผ R ์ด๋ผ๊ณ  ํ–ˆ์„ ๋•Œ ์–ด๋Š ํฌ์ธํ„ฐ๋ฅผ ์˜ฎ๊ฒจ์•ผ ์ตœ๋Œ€ ์ ์žฌ ์ปจํ…Œ์ด๋„ˆ๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ์„๊นŒ์š”?

๋งŒ์•ฝ R ์˜ ํฌ์ธํ„ฐ๋ฅผ ์™ผ์ชฝ์œผ๋กœ ์˜ฎ๊ธธ ๊ฒฝ์šฐ 2, 1, 4 ๋ง‰๋Œ€ ๋ชจ๋‘ R ๋ณด๋‹ค ์ž‘๊ธฐ ๋•Œ๋ฌธ์— ์ ˆ๋Œ€ ๋” ํฐ ์ปจํ…Œ์ด๋„ˆ๋ฅผ ๊ตฌํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.
์ด๋Š” ๊ฐ ์ปจํ…Œ์ด๋„ˆ์˜ ๋ถ€ํ”ผ๊ฐ€ ๋‘ ๋ง‰๋Œ€์ค‘ ๋” ์ž‘์€ ๋ง‰๋Œ€๊ธฐ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋†’์ด๊ฐ€ ๊ฒฐ์ •๋˜๊ธฐ ๋•Œ๋ฌธ์ด์ฃ .
๋Œ€์‹ ์— L ์„ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์˜ฎ๊ธธ ๊ฒฝ์šฐ L ๋ณด๋‹ค ํฐ ๋ง‰๋Œ€๊ธฐ๊ฐ€ ์กด์žฌํ•  ๊ฒฝ์šฐ ๋” ํฐ ์ปจํ…Œ์ด๋„ˆ๋ฅผ ๊ตฌํ•  ๊ฐ€๋Šฅ์„ฑ ์ด ์กด์žฌํ•ฉ๋‹ˆ๋‹ค.

๋”ฐ๋ผ์„œ ํ˜„์žฌ ๋‘ ํฌ์ธํ„ฐ๊ฐ€ ๊ฐ€๋ฅดํ‚ค๋Š” ๋ง‰๋Œ€ ์ค‘ ๋” ๋‚ฎ์€ ๋†’์ด๋ฅผ ๊ฐ€์ง€๋Š” ๋ง‰๋Œ€์ชฝ์˜ ํฌ์ธํ„ฐ๋ฅผ ์•ˆ์ชฝ์œผ๋กœ ์˜ฎ๊ฒจ์ฃผ๋ฉด์„œ ํƒ์ƒ‰์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function (height) {
  let answer = 0;
  let left = 0,
    right = height.length - 1;

  while (left < right) {
    const size = Math.min(height[left], height[right]) * (right - left);
    answer = Math.max(answer, size);
    if (height[left] < height[right]) left++;
    else right--;
  }

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

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

LeetCode 560 - Subarray Sum Equals K (Medium)  (2) 2021.03.04
LeetCode 752 - Open the Lock (Medium)  (0) 2021.03.04
LeetCode 763 - Partition Labels (Medium)  (0) 2021.03.04
LeetCode 48 - Rotate Image (Medium)  (0) 2021.03.04
LeetCode 236 - Lowest Common Ancestor of a Binary Tree (Medium)  (0) 2021.03.04

๐Ÿ’ฌ ๋Œ“๊ธ€