Search code examples
javaif-statementdouble-pointer

Leetcode #11 Container With Most Water: Why have to use 'else'


Leetcode #11 Container With Most Water

https://leetcode.com/problems/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 the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.

Notice that you may not slant the container.

My code is:

class Solution {
    public int maxArea(int[] height) {
        int l=0, r=height.length-1;
        int ans=0;
        while(l<r){
            int area= Math.min(height[l],height[r])*(r-l);
            ans=Math.max(ans,area);
            if(height[l]<=height[r]){
                l++;
            }
            if(height[l]>height[r]){
                r--;
            }
        }
        return ans;
    }
}

However the right answer is:

class Solution {
    public int maxArea(int[] height) {
        int l=0, r=height.length-1;
        int ans=0;
        while(l<r){
            int area= Math.min(height[l],height[r])*(r-l);
            ans=Math.max(ans,area);
            if(height[l]<=height[r]){
                l++;
            }
            else{
                r--;
            }
        }
        return ans;
    }
}

The only different between them is that I use if(height[l]>height[r]) rather than else

But with my code, input: [1,8,6,2,5,4,8,3,7] Output: 40 Expected: 49

I don't know why and what's the difference between them.


Solution

  • Notice that if the first condition is valid, the variable l is increased before evaluating the second condition, which means your comparing different array items in both conditions. Therefore, in some cases both conditions are true