简繁EN

LeetCodeNo. 090

【LeetCode with Python】 11. Container With Most Water

目錄

題目

原題頁面:https://leetcode.com/problems/container-with-most-water/
題目型別:Array, Two Pointers
難度評價:Medium
類似題目:(H) Trapping Rain Water

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.


分析

貪婪法的思想,用兩個指標從陣列的左邊和右邊開始,向中間搜尋。依據的理由有兩點:
1、因為一開始底邊長就已經是最大,兩個指標向中間移動的時候,底邊長只會變短,因此如果此時面積要變大的話,只能是兩條高中的最短者比移動前的最短高更高,否則就無需考察,直接continue到下一次的迴圈。
2、因此,每次選擇移動左指標還是右指標,優先選擇當前高度最短的那個,以期尋找到更高的邊。如果此時選擇移動當前高度最高的那個,就有可能跳過了最優解。


程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
# @return an integer
def maxArea(self, height):
len_height = len(height)
if 1 == len_height:
return 0
max_area = 0
left_index = 0
right_index = len_height - 1
while left_index < right_index:
if height[left_index] < height[right_index]:
area = (right_index - left_index) * height[left_index]
left_index += 1
else:
area = (right_index - left_index) * height[right_index]
right_index -= 1
if area > max_area:
max_area = area
return max_area

本文地址:https://xnerv.wang/zh-tw/leetcode-container-with-most-water/