Algorithms and Data Structures/Coding Practices

[LeetCode] 11 Container With Most Water

brightlightkim 2022. 5. 18. 14:09

Question: 

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

Notice that you may not slant the container.

 

Example 1:

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example 2:

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

My First Approach:

Brute Force using n^2 algorithm. However, it did not pass the test. It caused the runtime error. So I used a pointer instead. 

 

Answer:

class Solution {
    public int maxArea(int[] height) {
        int max = 0;
        int l = 0;
        int r = height.length-1;
        while (l < r){
            max = Math.max(max, (r-l)*Math.min(height[l], height[r]));
            if (height[l] > height[r]){
                r--;
            } else {
                l++;
            }
        }
        return max;
    }
}

Always answer is so simple..

'Algorithms and Data Structures > Coding Practices' 카테고리의 다른 글

CCI 4.1 Route Between Nodes  (0) 2022.05.31
[Stacks and Queues] CCI 3.1  (0) 2022.05.22
[LinkedList] CCI 2.1  (0) 2022.05.20
[LeetCode] 36. Valid Sudoku  (0) 2022.05.19
[Array and Strings] CCI 1.1  (0) 2022.05.18