Leet - 11

Having fun on Leetcode with C++, Java, Python & GO

Problem 11. Container With Most Water

My attempt(s)

Code

Java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
    public int maxArea(int[] height) {
        int ans = 0;
        int temp = 0;
        for (int i = 0; i < height.length; i++){
            for (int j = height.length-1; j > i; j--){
                if (height[j]>=height[i]){
                    temp = height[i]*(j-i);
                    if (temp>ans)
                        ans = temp;
                    break;
                }
            }
        }
        for (int i = height.length-1; i > -1; i--){
            for (int j = 0; j < i; j++){
                if (height[j]>=height[i]){
                    temp = height[i]*(i-j);
                    if (temp>ans)
                        ans = temp;
                    break;
                }
            }
        }
        return ans;
    }
}

Java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
    public int maxArea(int[] height) {
        int i=0;
        int j=height.length-1;
        
        int ans=0;
        while(i!=j){
            
            int area=(j-i)*Math.min(height[i],height[j]);
            
            if(area>ans){
                ans=area;
            }
            
            if(height[i]>height[j]){
                j--;
            }else{
                i++;
            }
        }
        return ans;
    }
}

Explanation of idea

Good solution ref.

Code

Analysis

Licensed under CC BY-NC-SA 4.0