-
[LeetCode] 11. Container With Most Water (JAVA)Algorithm 2023. 8. 26. 17:51728x90
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
Constraints:
n == height.length 2 <= n <= 105 0 <= height[i] <= 104
Solution:
public class No11ContainerWithMostWater { public int maxArea(int[] heights) { int left = 0; int right = heights.length - 1; int largestArea = 0; while (left < right) { int leftHeight = heights[left]; int rightHeight = heights[right]; int area = Math.min(rightHeight, leftHeight) * (right - left); largestArea = Math.max(area, largestArea); if (leftHeight > rightHeight) { right--; } else{ left++; } } return largestArea; } }
728x90'Algorithm' 카테고리의 다른 글
[Programmers] 추억 점수 (JAVA) (0) 2023.08.30 [Programmers] 달리기경주 (JAVA) (0) 2023.08.30 [Leetcode] 8. String To Integer(atoi) Typescript (0) 2023.01.24 [Leetcode] 7. Reverse Integer Typescript (0) 2022.08.25 [Leetcode] 6. Zigzag Conversion Typescript (0) 2022.08.25