|
| 1 | +public class Geegong { |
| 2 | + |
| 3 | + /** |
| 4 | + * two pointer ๋ฅผ ์ฌ์ฉ, ์ฒ์์๋ height ๋ฐฐ์ด์ ์ ๋ ฌํด์ ๋์ ์์ค๋ฅด ์ต๋ ๋ฉด์ ์ ๊ตฌํ๋๊ฑด๊ฐ ์ถ์์ง๋ง ๊ทธ๋ด ํ์๋ ์์์ |
| 5 | + * (์ด์ฐจํผ ๋ชจ๋ ์์๋ฅผ ๋์์ผ๋๊ธฐ ๋๋ฌธ์ ์ํ
์ ์๋ฏธ๊ฐ ์์, ๊ทธ๋ฆฌ๊ณ NLogN ์๊ฐ ๋ณต์ก๋๊ฐ ์๊ฒจ์ ๋ ์ข์ง ์์) |
| 6 | + * time complexity : O(N) |
| 7 | + * space complexity : O(N) |
| 8 | + * |
| 9 | + * @param height |
| 10 | + * @return |
| 11 | + */ |
| 12 | + public int maxArea(int[] height) { |
| 13 | + |
| 14 | + |
| 15 | + int leftIdx=0; |
| 16 | + int rightIdx = height.length - 1; |
| 17 | + int maxVolume = 0; |
| 18 | + |
| 19 | + while(leftIdx < rightIdx) { |
| 20 | + |
| 21 | + int leftHeight = height[leftIdx]; |
| 22 | + int rightHeight = height[rightIdx]; |
| 23 | + int gap = rightIdx - leftIdx; |
| 24 | + int currentVolume = gap * Math.min(leftHeight, rightHeight); |
| 25 | + maxVolume = Math.max(currentVolume, maxVolume); |
| 26 | + |
| 27 | + if (leftHeight > rightHeight) { |
| 28 | + rightIdx--; |
| 29 | + } else { |
| 30 | + leftIdx++; |
| 31 | + } |
| 32 | + |
| 33 | + } |
| 34 | + |
| 35 | + return maxVolume; |
| 36 | + |
| 37 | + |
| 38 | + |
| 39 | + |
| 40 | + |
| 41 | + |
| 42 | + |
| 43 | + |
| 44 | +////////// ์๋ ๋ถ๋ถ์ ์์ ๊ธฐ์์์ ํ์๋ ๋ฐฉ๋ฒ |
| 45 | +// int leftIndex = 0; |
| 46 | +// int rightIndex = height.length - 1; |
| 47 | +// |
| 48 | +// int maxAmount = 0; |
| 49 | +// int currentAmount = 0; |
| 50 | +// |
| 51 | +// while(leftIndex != rightIndex && leftIndex < rightIndex) { |
| 52 | +// // ๋ฉด์ ์ ๋จผ์ ๊ตฌํด๋ณธ๋ค. |
| 53 | +// int minHeight = Math.min(height[leftIndex], height[rightIndex]); |
| 54 | +// currentAmount = minHeight * (rightIndex - leftIndex); |
| 55 | +// |
| 56 | +// maxAmount = Math.max(currentAmount, maxAmount); |
| 57 | +// // ์ด๋ ํฌ์ธํฐ๋ฅผ ์์ง์ผ์ง ๊ฒฐ์ |
| 58 | +// /** |
| 59 | +// * case 1. ๋จ์ํ ์ ์ฒด๋ฅผ ๋ชจ๋ ํ์ด๋ฒ๋ฆฌ๋ฉด Time limit exceeded ๋ฐ์ |
| 60 | +// */ |
| 61 | +//// if (leftIndex < rightIndex - 1) { |
| 62 | +//// rightIndex--; |
| 63 | +//// } else if (leftIndex == rightIndex - 1) { |
| 64 | +//// rightIndex = height.length - 1; |
| 65 | +//// leftIndex++; |
| 66 | +//// } |
| 67 | +// |
| 68 | +// /** |
| 69 | +// * case 2. ํฌ์ธํฐ๊ฐ ๋๋ฉด์ ๋์ height๋ง ๊ณ ๋ คํด์ ํฌ์ธํฐ๊ฐ ์์ง์ผ ๋์๋ Time limit exceeded ๋ฐ์ X |
| 70 | +// */ |
| 71 | +// if (height[leftIndex] < height[rightIndex]) { |
| 72 | +// leftIndex++; |
| 73 | +// } else if (height[leftIndex] > height[rightIndex]) { |
| 74 | +// rightIndex--; |
| 75 | +// } else { |
| 76 | +// rightIndex--; |
| 77 | +// leftIndex++; |
| 78 | +// } |
| 79 | +// } |
| 80 | +// |
| 81 | +// return maxAmount; |
| 82 | + } |
| 83 | +} |
| 84 | + |
0 commit comments