[문제풀이] Leetcode 11. Container With Most Water 자바 풀이

kai6666·2022년 6월 26일
0


👉 문제

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

입출력 예시:

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.

✨ 풀이

public class ContainerWithMostWater {
    public static void main(String[] args) {
        int[] test = new int[]{1, 8, 6, 2, 5, 4, 8, 3, 7}; // 49
        System.out.println(maxArea(test));
    }
    private static int maxArea(int[] height) {
        int i = 0;
        int j = height.length - 1;

        int ans = 0;
        while(i != j) {
            int area = (j - i) * Math.min(height[i], height[j]);

            if(area >= ans) {
                ans = area;
            }
            if(height[i]>height[j]) {
                    j--;
                } else {
                    i++;
                }
            } return ans;
        }

    }

풀이 방식:

  • 넓이를 위한 가로 길이를 구하기 위해 0에서 시작하는 i라는 수와 맨끝에서 시작하는 j라는 수를 만들어준다.
  • 넓이에 쓰일 가로 길이는 j-i가 된다.
  • 가능한 긴 길이에서 중심으로 좁혀오며, 세로길이가 어느쪽에서 더 짧아지느냐에 따라 가로 길이를 좌우에서 한 번씩 줄여준다.
  • ans라는 값을 계속 갱신해줌으로써 최대넓이를 찾아낸다.
profile
성장 아카이브

0개의 댓글

관련 채용 정보