Tuesday, August 25, 2015

Container With Most Water

Problem Description
Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.
Solution
In this problem, we use 2 pointers, one runs from the 0, one runs backward.

  1. public class Solution {  
  2.     public int maxArea(int[] height) {  
  3.         //we assume the array height.length > 0  
  4.         int max = 0;  
  5.         int area;  
  6.         for(int i=0, j=height.length-1; i<j;){  
  7.               
  8.             if(height[i] > height[j]){  
  9.                 area = (j-i) * height[j];  
  10.                 j--;  
  11.             }else {  
  12.                 area = (j-i) * height[i];  
  13.                 i++;  
  14.             }  
  15.             if(area > max) max = area;  
  16.         }  
  17.         return max;  
  18.     }  
  19. }  

No comments:

Post a Comment