Container With Most Water
Q:
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (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.
A:
先取两端,比它大的必定要么向左移一步,要么向右移一步,如果两端高度相等,左各移一步。
要想到的话还是有点困难。
class Solution { public: int maxArea(vector<int> &height) { // Start typing your C/C++ solution below // DO NOT write int main() function int head = 0; int tail = height.size() - 1; int res = 0; while (head < tail) { int cur_h = min(height[head], height[tail]) * (tail - head); res = max(res, cur_h); int tmp = head; if (height[head] <= height[tail]) head++; if (height[tmp] >= height[tail]) tail--; } return res; } };
Passion, patience, perseverance, keep it and move on.

浙公网安备 33010602011771号