Software Enginner πŸ‡―πŸ‡΅ and πŸ‡°πŸ‡·

Leetcode - Container With Most Water

Series. Leetcode Algorithm - Two Pointer & Sliding Window

  1. Leetcode - Container With Most Water - 2022-03-28 11:26:00 +0000
  2. Leetcode - Longest Substring Without Repeating Charactes - 2022-03-28 11:12:00 +0000
Problem Container With Most Water
Difficulty Medium
Language Java

Problem,

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.

Solution,

Two Pointer 둜 μ‰½κ²Œ ν’€ 수 μžˆλ‹€. μ§‘ν•©μ˜ 첫 번째 μ›μ†Œμ™€ λ§ˆμ§€λ§‰ μ›μ†Œλ₯Ό κΈ°μ€€μœΌλ‘œ 작고, 더 μž‘μ€ μͺ½μ΄ μ–Έμ œλ‚˜ 기쀀이 λœλ‹€.

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