codekofi
← All questions

Container With Most Water

HardTwo Pointers

The problem

Each element is the height of a vertical line at that index. Pick two lines so that they and the x-axis form a container.

Return the largest area of water such a container can hold.

maxArea({1, 8, 6, 2, 5, 4, 8, 3, 7})

One of these three is correct

Two lines apart, at the closest.

The wrong ones are this same code with between two and five lines changed. Some of those changes do not compile. There is no Run button: running all three would turn this into a vote rather than a reading.

1int maxArea(const vector<int>& nums) {
2
3 if (!(nums.empty())) {
4 return 0;
5 }
6
7 int left = 0;
8 int right = nums.size() - 1;
9 int ans = 0;
10
11 while (left < right) {
12
13 int height = max(nums[left], nums[right]);
14 int width = right - left;
15 int area = height * width;
16
17 if (area > ans) {
18 ans = area;
19 }
20
21 if (nums[left] < nums[right]) {
22 left++;
23 } else {
24 right--;
25 }
26 }
27
28 return ans;
29}
1int maxArea(const vector<int>& nums) {
2
3 if (nums.empty()) {
4 return 0;
5 }
6
7 int left = 0;
8 int right = nums.size() - 1;
9 int ans = 0;
10
11 while (left < right) {
12
13 int height = min(nums[left], nums[right]);
14 int width = right - left;
15 int area = height * width;
16
17 if (area > ans) {
18 ans = area;
19 }
20
21 if (nums[left] < nums[right]) {
22 left++;
23 } else {
24 right--;
25 }
26 }
27
28 return ans;
29}
1int maxArea(const vector<int>& nums) {
2
3 if (nums.empty()) {
4 return 0;
5 }
6
7 int left = 0;
8 int right = nums.size() - 1;
9 int ans = 1;
10
11 while (left < right) {
12
13 int height = max(nums[left], nums[right]);
14 int width = right - left;
15 int area = height * width;
16
17 if (area > ans) {
18 ans = area;
19 }
20
21 if (nums[left] < nums[right]) {
22 left++;
23 } else {
24 right--;
25 }
26 }
27
28 return ans;
29}