1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| #include <iostream> #include <vector> #include <algorithm> using namespace std;
class Solution_0 { public: int maxArea(vector<int>& height) { int n = height.size(); int maxArea = 0;
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(vector<int>& height) { int res = 0; int i = 0, j = height.size()-1;
while (i < j) { int area = min(height[i], height[j]) * (j - i); res = max(res, area); if (height[i] < height[j]) { i++; } else { j--; } }
return res; } };
void printArray(const vector<int>& nums) { cout << "["; for (size_t i = 0; i < nums.size(); i++) { cout << nums[i]; if (i != nums.size() - 1) cout << ","; } cout << "]"; }
int main() { Solution solution; vector<vector<int>> height_cases = { {1,8,6,2,5,4,8,3,7}, {1,1} };
for (auto& nums : height_cases) { int result = solution.maxArea(nums);
cout << "Input: "; printArray(nums); cout << endl; cout << "Output: " << result << endl; } return 0; }
|