Skip to content
This repository has been archived by the owner on Oct 14, 2021. It is now read-only.

Container with Most Water [Java-Solution required] #527

Merged
merged 2 commits into from
Oct 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@

import java.util.*;

public class containerWithMostWater
{

// method to calculate area of container with max water
public static int calculateArea(int[] arr, int n)
{
int left = 0; // co-ordinate of left wall
int right = n-1; // co-ordinate of right wall
int maxArea=0; // store of area of conatainer with max water

// lopoing till left wall crosses right wall
while(left < right)
{

// height of container will be height of smaller wall
// base length will be how far they are apart i.e., right - left

int area = Math.min(arr[left],arr[right])*(right-left);


// storing the max calculated area of container
maxArea = Math.max(maxArea, area);

// moving towards right to find left wall of higher height
if(arr[left] < arr[right])
left++;

// moving towards left to find right wall of higher height
else
right--;

}
return maxArea;
}

// driver program
public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);

int n = sc.nextInt(); // number of walls
int arr[] = new int[n]; // for storing height of walls

for(int i = 0;i < n; i++)
arr[i] = sc.nextInt(); // input height of walls


System.out.println(calculateArea(arr, n));
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
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.

Example 1:
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49

Example 2:
Input: height = [1,1]
Output: 1


Example 3:
Input: height = [4,3,2,1,4]
Output: 16

Example 4:
Input: height = [1,2,1]
Output: 2