From f610c45a4a94944ce195af4e877f0288b4296e0c Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Wed, 22 Oct 2014 17:42:21 +0800 Subject: [PATCH] Add comments for "Container With Most Water" --- .../containerWithMostWater.cpp | 25 ++++++++++++------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/src/containerWithMostWater/containerWithMostWater.cpp b/src/containerWithMostWater/containerWithMostWater.cpp index 14daa43..4d2b9c7 100644 --- a/src/containerWithMostWater/containerWithMostWater.cpp +++ b/src/containerWithMostWater/containerWithMostWater.cpp @@ -17,16 +17,23 @@ class Solution { public: int maxArea(vector &height) { - int area = 0; - int i = 0; - int j = height.size()-1; - - while(iheight[j] ? height[j] : height[i]); - area = a>area ? a : area; - height[i]>height[j] ? j-- : i++; + + int maxArea = 0; + // two pointers scan from two sides to middle + int left = 0; + int right = height.size()-1; + + int area; + while ( left < right ){ + //calculate the area + area = (right - left) * ( height[left] < height[right] ? height[left] : height[right]); + //tracking the maxium area + maxArea = area > maxArea ? area : maxArea; + // because the area is decided by the shorter edge + // so we increase the area is to increase the shorter edge + height[left] < height[right] ? left++ : right-- ; } - return area; + return maxArea; } };