11. Container With Most Water(头尾双指针)

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.

思路:每次移动矮的那侧的指针,并且只关心比原来高的情况(因为宽度已经减小了,高度必须增高才可能面积变大)

int maxArea(int* height, int heightSize) {
    int start = 0; 
    int end = heightSize-1;
    int ret = 0;
    int maxStart = 0;
    int maxEnd = 0;

    while(start < end){
        if(height[start] < height[end]){
            if(height[start]*(end-start) > ret) ret = height[start]*(end-start);
            while(start<end){
                start++;
                if(height[start] > maxStart){
                    maxStart = height[start];
                    break;
                }
            }
        }
        else{
            if(height[end]*(end-start) > ret) ret = height[end]*(end-start);
            while(start<end) {
                end--;
                if(height[end] > maxEnd){
                    maxEnd = height[end];
                    break;
                }
            }
        }
    }
    
    return ret;
}
原文地址:https://www.cnblogs.com/qionglouyuyu/p/5368310.html