|
| 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