Problem:
Given n non-negative integers a1, A2, ..., an, where each represents a point at coordinate (I, AI). n vertical lines is drawn such, the and the other endpoints of line I am at (i, AI) and (i, 0). Find lines, which together with X-axis forms a container, such that the container contains the most water. Note:you may not slant the container.
The x-axis is the bottom, two longitudinal axes are changed, the volume of the container is obtained, and the short edge is the bottleneck.
Thinking:
(1) The short side determines the effective height of the tank, the bottom to be as wide as possible.
(2) A typical double-pointer solution.
(3) Greedy strategy, which side is short, narrowing in the search for the next edge.
Code
Class Solution {public: int Maxarea (vector<int> &height) { //Start Typing your C + + solution Below
//does not write int main () function int i = 0; Int J = height.size ()-1; int ret = 0; while (I < j) { int area = (j-i) * min (Height[i], height[j]); RET = max (ret, area); if (Height[i] <= height[j]) i++; else j--; } return ret; }};
Time Complexity of O (n)
Brute force method: Time Complexity O (n*n)
int area (Vector<int>::iterator &a,vector<int>::iterator &b) { return (b-a) * (*a>*b?*b:*a) ;} Class Solution {public: int Maxarea (vector<int> &height) { int max_area=0; For (Vector<int>::iterator I=height.begin () +1;i!=height.end (), i++) {for (VECTOR<INT>:: Iterator J=height.begin (); j!=i;j++) { Max_area=max (Max_area,area (j,i)); } } return max_area;} ;
Leetcode | | Container with most water issues