Given n non-negative integers A1, A2, ..., an, where each represents a point at Coordi Nate (i, ai). N Vertical Lines is drawn such that the the both 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.
Problem: An array of A1,A2 given n elements. An, they correspond to the n lines in the coordinates, and the two ends of the line I are coordinates (i, 0) and (i, AI) respectively. Find two lines, these two lines and the x-axis formed by the container can fill the most water.
This is a histogram-related topic, as well as the title of the histogram: trapping Rain water and largest Rectangle in histogram. Their solution has a similar place, that is, the use of incremental elements and corresponding subscript to calculate.
- Find out from left to right increment element Ls, and increment element Rs from right to left .
- Using the elements of Ls to form a container in sequence with the elements of Rs, the maximum value found in all the results is the solution of the original problem.
Optimization point: The second part of the multiplication time, when ls[i] < Rs[k] time, ls[i] and other greater than rs[k] combination can no longer calculate, necessarily less than ls[i] and rs[k].
1 intMaxarea (vector<int>&height) {2 3 if(Height.size () <2){4 return 0;5 }6 7vector<int>Idxascel;8 9Idxascel.push_back (0);Ten One for(inti =1; I < height.size (); i++) { A - if(Height[i] >Height[idxascel.back ()]) { - Idxascel.push_back (i); the } - } - -vector<int>Idxascer; +Idxascer.push_back ((int) Height.size ()-1); - + for(inti = (int) Height.size ()-2; I >= idxascel.back (); i--) { A if(Height[i] >Height[idxascer.back ()]) { at Idxascer.push_back (i); - } - } - - intMaxA =0; - for(inti =0; I < idxascel.size (); i++) { in for(intK =0; K < Idxascer.size (); k++) { - to intL =Idxascel[i]; + intR =Idxascer[k]; - the inth =min (height[l], height[r]); * $ intLen = R-l;Panax NotoginsengMaxA = Max (MaxA, H *len); - the if(Height[l] <=Height[r]) { + Break; A } the } + } - $ returnMaxA; $}
[Leetcode] 11. Container with most water My submissions Question problem Solving ideas