Container With Most Water – Leetcode #11

PROBLEM STATEMENT

This problem is from Leetcode – Container With Most Water. Problem statement i short is as below:

Given an array of line heights, find two lines that form a container holding the most water. Return the maximum area, where area = distance × min height.

SOLUTION

FIRST APPROACH

public int maxArea(int[] height) {

		int maxArea = 0;

		int altitude = 0;
		int width = 0;
		
		// start right from 1 and keep increasing
		for(int right=1; right< height.length; right++) {
			
			// start left from 0 and go towards right
			for(int left=0; left<right; left++) {
				
				altitude = Math.min(height[left] , height[right]);
		    	width = right - left;
		    	maxArea = Math.max(maxArea, altitude*width);
			}
					
		}
				
		return maxArea;
	}

You can checkout the code from Github here – Container With Most Water – First Approach.

PERFORMANCE ANALYSIS

COMPLEXITYO (N2)

SECOND APPROACH

public int maxArea(int[] height) {
		    
		    int maxArea = 0;
		    int left = 0;
		    int right = height.length-1;
		    int altitude = 0;
		    int width = 0;
		    
		    while(left <= right) {
		    			    	
		    	altitude = Math.min(height[left] , height[right]);
		    	width = right - left;
		    	maxArea = Math.max(maxArea, altitude*width);
		    	
		    	// compare the two heights and move towards bigger
		    	if(height[left] < height[right])
		    		left++;
		    	else
		    		right--;	    	
		    	
		    }
		    	    
		    return maxArea;
	    }

You can checkout the code from Github here – Container With Most Water – Second Approach.

PERFORMANCE ANALYSIS

RUNTIME5 ms | Beats 76.15 %
MEMORY57.80 MB | Beats 72.21 %
TIME COMPLEXITYO (N)
SPACE COMPLEXITYO (1)

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top