一道有趣的面試 :container with most 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 and n is at least 2.
這裏寫圖片描述

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:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49

題目大意是,給定若干條垂直線,順着x軸依次排列,要求找出其中最大的裝水面積。

解法一:暴力求解
枚舉任意兩個垂直線,複雜度是O(N^2)。
這個方法很容易理解,不做解釋。

解法二:貪心求解
維護左邊界 L 和右邊界 R ,邊界之間的裝水面積是 C = min(Input[L], Input[R]) * (R-L)
之後更新左右邊界,如果Input[L] < Input[R],則左邊界+1,否則右邊界-1。
複雜度爲O(N)。
這個方法很巧妙,但是理解起來不是那麼直觀。

這也是這道題目最有趣的地方,給大家分享一個理解思路:
可以把這個過程理解爲每次減少不必要的計算,
如果Input[L] < Input[R],那麼[L, R-1]的裝水面積一定小於[L, R],思考一下爲什麼?原因如下:
由於裝水面積取決於兩個部分:邊界間距 R-L,邊界之間的較小者(木桶原理)。
顯然[L, R-1]的邊界間距小於[L, R]
min(Input[L], Input[R-1]) <= min(Input[L], Input[R]),這個條件是成立的,不論Input[R-1]的值是多少。

所以,最終答案一定不在[L, R-1]內,可以將左邊界+1,剩餘的可能性存在於[L+1, R]中。

最後再留一個問題:
如果Input[L] == Input[R],此時應該移動哪個邊界,爲什麼?

給出這個題目的鏈接:
https://leetcode.com/problems/container-with-most-water/description/


歡迎大家關注我的公衆號

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章