Brute Force
Intuition
The simplest approach is to consider every possible pair of lines and compute the area formed between them. For each pair (i, j), the width is j - i and the height is the minimum of the two line heights. We track the maximum area seen across all pairs. This guarantees we find the optimal answer but runs in quadratic time.
Algorithm
- Initialize a variable maxArea to 0.
- Use two nested loops to consider every pair of indices (i, j) where i < j.
- For each pair, calculate the area as min(height[i], height[j]) * (j - i).
- Update maxArea if the current area is larger.
- Return maxArea after checking all pairs.
O(n^2)SpaceO(1)Code (C++ · Java · Python · Go)
class Solution {
public:
int maxArea(vector<int>& height) {
int maxArea = 0;
int n = height.size();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int area = min(height[i], height[j]) * (j - i);
maxArea = max(maxArea, area);
}
}
return maxArea;
}
};class Solution {
public int maxArea(int[] height) {
int maxArea = 0;
int n = height.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int area = Math.min(height[i], height[j]) * (j - i);
maxArea = Math.max(maxArea, area);
}
}
return maxArea;
}
}def maxArea(height: list[int]) -> int:
max_area = 0
n = len(height)
for i in range(n):
for j in range(i + 1, n):
area = min(height[i], height[j]) * (j - i)
max_area = max(max_area, area)
return max_areafunc maxArea(height []int) int {
maxArea := 0
n := len(height)
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
h := min(height[i], height[j])
area := h * (j - i)
if area > maxArea {
maxArea = area
}
}
}
return maxArea
}
func min(a, b int) int {
if a < b {
return a
}
return b
}