Two Pointers approach for Container with Most Water
(height []int)
| 37 | |
| 38 | // Two Pointers approach for Container with Most Water |
| 39 | func maxAreaTwoPointers(height []int) int { |
| 40 | left, right := 0, len(height)-1 |
| 41 | maxArea := 0 |
| 42 | |
| 43 | // Move pointers toward each other |
| 44 | for left < right { |
| 45 | width := right - left // Distance between lines |
| 46 | minHeight := min(height[left], height[right]) // Compute height |
| 47 | area := minHeight * width // Compute water contained |
| 48 | |
| 49 | if area > maxArea { |
| 50 | maxArea = area // Update max water |
| 51 | } |
| 52 | |
| 53 | // Move the pointer pointing to the shorter height |
| 54 | if height[left] < height[right] { |
| 55 | left++ // Move left pointer forward |
| 56 | } else { |
| 57 | right-- // Move right pointer backward |
| 58 | } |
| 59 | } |
| 60 | return maxArea |
| 61 | } |
| 62 | |
| 63 | // Helper function to return the minimum of two integers |
| 64 | func min(a, b int) int { |