Saturday, August 19, 2017

LeetCode - 11. Container With Most Water

Source Link:
https://leetcode.com/problems/container-with-most-water/description/ 

Question:
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 line i is at (i, ai) 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 and n is at least 2. 

Hint:
https://leetcode.com/problems/container-with-most-water/solution/
 
My Solution:
Note:
1. Using "Two Pointer" Approach
int left = 0; // the left pointer
int right = length-1; // the right pointer
2. move the pointers (until left==right)
while( left != right)
3. area = width * height
int area = (right - left) * Math.min(height[left], height[right]);
4. the max area
max_area = Math.max(max_area, area);
5. move the lower one (to find bigger area)
if(height[left] < height[right])
left++;
else
right--;   
 
 

No comments:

Post a Comment

Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments

Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...