Container With Most Water Solutions in C++
Number 11
Difficulty Medium
Acceptance 50.9%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/container-with-most-water/// Author : Hao Chen// Date : 2014-06-22class Solution {public:int maxArea(vector<int> &height) {int maxArea = 0;// two pointers scan from two sides to middleint left = 0;int right = height.size()-1;int area;while ( left < right ){// calculate the areaarea = (right - left) * ( height[left] < height[right] ? height[left] : height[right]);// tracking the maxium areamaxArea = area > maxArea ? area : maxArea;// because the area is decided by the shorter edge// so we increase the area is to increase the shorter edge//// height[left] < height[right] ? left++ : right-- ;//// However, the above code could cause the unnecessary `area` cacluation// We can do some improvement as below:if (height[left] < height[right]) {do {left++;} while (left < right && height[left-1] >= height[left]);} else {do {right--;} while (right > left && height[right+1] >= height[right]);}}return maxArea;}};
C++ solution by pezy/LeetCode
#include <algorithm>#include <vector>using std::vector; using std::prev; using std::max; using std::min;class Solution {public:int maxArea(vector<int> &height) {int ret{0};for (auto beg = height.begin(), end = prev(height.end()); beg < end; *beg < *end ? ++beg : --end)ret = max(ret, static_cast<int>(end - beg)*min(*beg, *end));return ret;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/container-with-most-water//// Author : liuyubobobo/// Time : 2018-08-13#include <iostream>#include <vector>#include <cassert>using namespace std;/// Brute Force/// Time Complexity: O(n^2)/// Space Complexity: O(1)class Solution {public:int maxArea(vector<int>& height) {assert(height.size() >= 2);int area = 0;for(int i = 0 ; i < height.size() ; i ++)for(int j = i + 1; j < height.size() ; j ++)area = max(area , min(height[i], height[j]) * (j - i));return area;}};int main() {vector<int> nums1 = {1, 1};cout << Solution().maxArea(nums1) << endl;return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/container-with-most-water//// Author : liuyubobobo/// Time : 2016-12-26#include <iostream>#include <vector>#include <cassert>using namespace std;/// Two Pointers/// Time Complexity: O(n)/// Space Complexity: O(1)class Solution {public:int maxArea(vector<int>& height) {assert(height.size() >= 2);int l = 0, r = height.size() - 1;int area = 0;while(l < r){area = max(area , min(height[l], height[r]) * (r - l));if(height[l] < height[r])l ++;elser --;}return area;}};int main() {vector<int> nums1 = {1, 1};cout << Solution().maxArea(nums1) << endl;return 0;}