|
| 1 | +""" |
| 2 | +[결과 요약] |
| 3 | +# 시도한 로직 수: 3 |
| 4 | + 1. 모든 결과룰 순회하면서 시간복잡도 O(n^2)을 시도 -> LeetCode에서 Time Limit Exceed 발생 |
| 5 | + 2. 리스트 양쪽 끝에서 포인터를 이동하는 알고리즘: 시간/공간 모두 O(n) |
| 6 | + 3. (2)의 로직은 유지한 채로 코드 가독성을 개선(알고리즘의 흐름을 쉽게 이해할 수 있도록) |
| 7 | +""" |
| 8 | + |
| 9 | + |
| 10 | +class Solution: |
| 11 | + def maxArea(self, height: list[int]) -> int: |
| 12 | + left, right = 0, len(height) - 1 |
| 13 | + max_area = 0 |
| 14 | + |
| 15 | + while left < right: |
| 16 | + left_height, right_height = height[left], height[right] |
| 17 | + min_height = min(left_height, right_height) |
| 18 | + width = right - left |
| 19 | + |
| 20 | + current_area = width * min_height |
| 21 | + max_area = max(max_area, current_area) |
| 22 | + |
| 23 | + if left_height < right_height: |
| 24 | + left += 1 |
| 25 | + else: |
| 26 | + right -= 1 |
| 27 | + |
| 28 | + return max_area |
| 29 | + |
| 30 | + |
| 31 | +if __name__ == "__main__": |
| 32 | + test_cases = [ |
| 33 | + ([1, 1], 1), |
| 34 | + ([1, 2, 1], 2), |
| 35 | + ([4, 3, 2, 1, 4], 16), |
| 36 | + ([1, 8, 6, 2, 5, 4, 8, 3, 7], 49), |
| 37 | + ([1, 2, 4, 3], 4), |
| 38 | + ([2, 3, 10, 5, 7, 8, 9], 36), |
| 39 | + ([1, 3, 2, 5, 25, 24, 5], 24), |
| 40 | + ([5, 5, 5, 5, 5], 20), |
| 41 | + ([1, 1000, 1, 1000, 1], 2000), |
| 42 | + ([1, 2, 3, 4, 5, 6], 9), |
| 43 | + ] |
| 44 | + |
| 45 | + solution = Solution() |
| 46 | + for idx, case_ in enumerate(test_cases): |
| 47 | + height, answer = case_ |
| 48 | + result = solution.maxArea(height) |
| 49 | + assert ( |
| 50 | + answer == result |
| 51 | + ), f"Test Case {idx + 1} Failed: Expected {answer}, Got {result}" |
0 commit comments