Problem:
GivenNNon-negative integersA1,A2,...,An, Where each represents a point at coordinate (I,AI).NVertical lines are drawn such that the two endpoints of LineIIs (I,AI) And (I, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.
In the (x, y) Coordinate, after each vertex is in a straight line perpendicular to the X axis, find the two straight lines and the X axis can hold the most water, it does not mean the area of the trapezoid, but the rectangular area of the short board effect. First, I tried it and practiced it. N-party timeout is expected.
class Solution {public:int maxArea(vector<int> &height){ int area = 0, temparea; int *temp = new int[height.size()]; for (int i = 0; i < height.size(); i++) { int maxN = 0; for (int j = 0; j < height.size(); j++) { if (i != j) { temparea = (height[i]
Later I thought about whether or not I could sort the data and try again. I found that sort was unstable, so I gave up. Later, we found that the solution was to shrink from both sides. Two sum is also the first question on both sides.
Why should we use both sides to go inside, because the area we want is the distance between two straight lines * the value of the two straight lines that are short, so we should first set one, the maximum distance is the head and tail. If the distance is smaller than this distance and the distance is bigger than me, it is only possible to increase the distance, at this time, we will look forward at the corresponding position of the short article to see if it may be longer than the short one, and the area is larger than before. If it is larger, record it. Why do we need to look in the short way, because if it is long, it is the same as the long one. It is also based on the short board effect. According to this idea, I sorted out the following code:
class Solution {public:int maxArea(vector<int> &height){ int left = 0, right = height.size() - 1; int maxA = 0; while(left < right) { if (height[left] < height[right]) { int tmp = (right - left) * height[left]; left++; if (tmp > maxA) maxA = tmp; } else { int tmp = (right - left) * height[right]; if (tmp > maxA) maxA = tmp; right--; } } return maxA; }};
In this way, accept is enabled.
Leetcode 11th -- container with most water