<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                # 困雨水 > 原文: [https://www.geeksforgeeks.org/trapping-rain-water/](https://www.geeksforgeeks.org/trapping-rain-water/) 給定 n 個表示海拔圖的非負整數,其中每個條的寬度為 1,計算下雨后它能捕獲多少水。 **示例**: ``` Input: arr[] = {2, 0, 2} Output: 2 Explanation: The structure is like below We can trap 2 units of water in the middle gap. Input: arr[] = {3, 0, 2, 0, 4} Output: 7 Explanation: Structure is like below We can trap "3 units" of water between 3 and 2, "1 unit" on top of bar 2 and "3 units" between 2 and 4\. See below diagram also. Input: arr[] = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] Output: 6 Explanation: The structure is like below Trap "1 unit" between first 1 and 2, "4 units" between first 2 and 3 and "1 unit" between second last 1 and last 2 ``` [](https://practice.geeksforgeeks.org/problem-page.php?pid=281) ## 強烈建議您在繼續解決方案之前,單擊此處進行練習。 **基本見解**: 如果左右兩邊的條形較高,則數組的元素可以存儲水。 可以通過找到左側和右側條的高度來找出要存儲在每個元素中的水量。 這個想法是計算可以存儲在數組的每個元素中的水量。 **示例** 考慮數組{3,0,0,2,0,4},三個單位的水可以存儲三個索引 1 和 2,一個單位的水存儲在索引 3 中,并且 索引 4 處的三個水量。 > 對于 Array [] = {3,0,2,0,4} > 存儲的水= 0 + 3 + 1 + 3 + 0 = 7 > ![](https://img.kancloud.cn/bd/28/bd2825f5d987ac61e2ed11c758fcc2d4_722x322.png) **方法 1**: 這是上述問題的簡單解決方案。 * **方法**:想法是遍歷每個數組元素,并在左側和右側找到最高的條形。 取兩個高度中的較小者。 當前元素的較小高度和高度之間的差是可以存儲在此數組元素中的水量。 * **算法**: 1. 從頭到尾遍歷數組。 2. 對于每個元素,從開始到該索引遍歷數組,然后找到最大高度*(a)*,從當前索引遍歷該數組,然后找到最大高度*(b)* 。 3. 將在此列中存儲的水量為 *min(a,b)–數組[i]* ,將此值添加到存儲的總水量中 4. 打印存儲的水總量。 * **實現**: ## C++ ``` // C++ implementation of the approach #include<bits/stdc++.h>? using namespace std;? // Function to return the maximum // water that can be stored int maxWater(int arr[], int n)? { ????// To store the maximum water? ????// that can be stored ????int res = 0; ????// For every element of the array ????for (int i = 1; i < n-1; i++) { ????????// Find the maximum element on its left ????????int left = arr[i]; ????????for (int j=0; j<i; j++) ???????????left = max(left, arr[j]); ????????// Find the maximum element on its right??? ????????int right = arr[i]; ????????for (int j=i+1; j<n; j++) ???????????right = max(right, arr[j]);? ???????// Update the maximum water???? ???????res = res + (min(left, right) - arr[i]);??? ????} ????return res;? }? // Driver code int main()? {? ????int arr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};? ????int n = sizeof(arr)/sizeof(arr[0]);? ????cout << maxWater(arr, n);? ????return 0;? } ``` ## Python3 ``` # Python3 implementation of the approach? # Function to return the maximum? # water that can be stored? def maxWater(arr, n) : ????# To store the maximum water? ????# that can be stored? ????res = 0;? ????# For every element of the array? ????for i in range(1, n - 1) :? ????????# Find the maximum element on its left? ????????left = arr[i];? ????????for j in range(i) : ????????????left = max(left, arr[j]);? ????????# Find the maximum element on its right? ????????right = arr[i];? ????????for j in range(i + 1 , n) :? ????????????right = max(right, arr[j]); ????????# Update the maximum water ????????res = res + (min(left, right) - arr[i]);? ????return res;? # Driver code? if __name__ == "__main__" :? ????arr = [0, 1, 0, 2, 1, 0,? ???????????1, 3, 2, 1, 2, 1];? ????n = len(arr);? ????print(maxWater(arr, n));? # This code is contributed by AnkitRai01 ``` **輸出**: ``` 6 ``` * **復雜度分析**: * **時間復雜度**: `O(n^2)`。 有兩個遍歷數組的嵌套循環,因此時間復雜度為 `O(n^2)`。 * **空間復雜度**:`O(1)`。 不需要額外的空間。 **方法 2**: 這是解決上述問題的有效方法。 * **方法**:在先前的解決方案中,要在左側和右側找到最高的柱,需要遍歷數組,這會降低解決方案的效率。 為了提高效率,必須在線性時間內預先計算每個小節左右兩邊的最高小節。 然后使用這些預先計算的值查找每個數組元素中的水量。 * **算法**: 1. 創建兩個數組*,左側*,右側*,右側*,大小為 n。 創建一個變量 *max_ = INT_MIN* 。 2. 從頭到尾運行一個循環。 在每次迭代中,將 max_ 更新為 *max_ = max(max_,arr [i])*,并向左分配 *[i] = max_* 3. 更新 max_ = INT_MIN。 4. 從頭到尾運行另一個循環。 在每次迭代中,將 max_ 更新為*,max_ = max(max_,arr [i])*,并指定 *right [i] = max_* 5. 從頭到尾遍歷數組。 6. 將在此列中存儲的水量為 *min(a,b)– array [i]* ,(其中 a = left [i]和 b = right [i])將此值加到 儲水總量 7. 打印存儲的水總量。 * **實現**: ## C++ ``` // C++ program to find maximum amount of water that can // be trapped within given set of bars. #include <bits/stdc++.h> using namespace std; int findWater(int arr[], int n) { ????// left[i] contains height of tallest bar to the ????// left of i'th bar including itself ????int left[n]; ????// Right [i] contains height of tallest bar to ????// the right of ith bar including itself ????int right[n]; ????// Initialize result ????int water = 0; ????// Fill left array ????left[0] = arr[0]; ????for (int i = 1; i < n; i++) ????????left[i] = max(left[i - 1], arr[i]); ????// Fill right array ????right[n - 1] = arr[n - 1]; ????for (int i = n - 2; i >= 0; i--) ????????right[i] = max(right[i + 1], arr[i]); ????// Calculate the accumulated water element by element ????// consider the amount of water on i'th bar, the ????// amount of water accumulated on this particular ????// bar will be equal to min(left[i], right[i]) - arr[i] . ????for (int i = 0; i < n; i++) ????????water += min(left[i], right[i]) - arr[i]; ????return water; } // Driver program int main() { ????int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; ????int n = sizeof(arr) / sizeof(arr[0]); ????cout << "Maximum water that can be accumulated is " ?????????<< findWater(arr, n); ????return 0; } ``` ## Java ``` // Java program to find maximum amount of water that can // be trapped within given set of bars. class Test { ????static int arr[] = new int[] { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; ????// Method for maximum amount of water ????static int findWater(int n) ????{ ????????// left[i] contains height of tallest bar to the ????????// left of i'th bar including itself ????????int left[] = new int[n]; ????????// Right [i] contains height of tallest bar to ????????// the right of ith bar including itself ????????int right[] = new int[n]; ????????// Initialize result ????????int water = 0; ????????// Fill left array ????????left[0] = arr[0]; ????????for (int i = 1; i < n; i++) ????????????left[i] = Math.max(left[i - 1], arr[i]); ????????// Fill right array ????????right[n - 1] = arr[n - 1]; ????????for (int i = n - 2; i >= 0; i--) ????????????right[i] = Math.max(right[i + 1], arr[i]); ????????// Calculate the accumulated water element by element ????????// consider the amount of water on i'th bar, the ????????// amount of water accumulated on this particular ????????// bar will be equal to min(left[i], right[i]) - arr[i] . ????????for (int i = 0; i < n; i++) ????????????water += Math.min(left[i], right[i]) - arr[i]; ????????return water; ????} ????// Driver method to test the above function ????public static void main(String[] args) ????{ ????????System.out.println("Maximum water that can be accumulated is " + findWater(arr.length)); ????} } ``` ## Python3 ``` # Python program to find maximum amount of water that can # be trapped within given set of bars. def findWater(arr, n): ????# left[i] contains height of tallest bar to the ????# left of i'th bar including itself ????left = [0]*n ????# Right [i] contains height of tallest bar to ????# the right of ith bar including itself ????right = [0]*n ????# Initialize result ????water = 0 ????# Fill left array ????left[0] = arr[0] ????for i in range( 1, n): ????????left[i] = max(left[i-1], arr[i]) ????# Fill right array ????right[n-1] = arr[n-1] ????for i in range(n-2, -1, -1): ????????right[i] = max(right[i + 1], arr[i]); ????# Calculate the accumulated water element by element ????# consider the amount of water on i'th bar, the ????# amount of water accumulated on this particular ????# bar will be equal to min(left[i], right[i]) - arr[i] . ????for i in range(0, n): ????????water += min(left[i], right[i]) - arr[i] ????return water # Driver program arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] n = len(arr) print("Maximum water that can be accumulated is", findWater(arr, n)) # This code is contributed by # Smitha Dinesh Semwal ``` ## C# ``` // C# program to find maximum amount of water that can // be trapped within given set of bars. using System; class Test { ????static int[] arr = new int[] { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; ????// Method for maximum amount of water ????static int findWater(int n) ????{ ????????// left[i] contains height of tallest bar to the ????????// left of i'th bar including itself ????????int[] left = new int[n]; ????????// Right [i] contains height of tallest bar to ????????// the right of ith bar including itself ????????int[] right = new int[n]; ????????// Initialize result ????????int water = 0; ????????// Fill left array ????????left[0] = arr[0]; ????????for (int i = 1; i < n; i++) ????????????left[i] = Math.Max(left[i - 1], arr[i]); ????????// Fill right array ????????right[n - 1] = arr[n - 1]; ????????for (int i = n - 2; i >= 0; i--) ????????????right[i] = Math.Max(right[i + 1], arr[i]); ????????// Calculate the accumulated water element by element ????????// consider the amount of water on i'th bar, the ????????// amount of water accumulated on this particular ????????// bar will be equal to min(left[i], right[i]) - arr[i] . ????????for (int i = 0; i < n; i++) ????????????water += Math.Min(left[i], right[i]) - arr[i]; ????????return water; ????} ????// Driver method to test the above function ????public static void Main() ????{ ????????Console.WriteLine("Maximum water that can be accumulated is " + findWater(arr.Length)); ????} } // This code is contributed by vt_m. ``` ## PHP ``` <?php // PHP program to find maximum // amount of water that can // be trapped within given set of bars. function findWater($arr, $n) { ????// left[i] contains height of ????// tallest bar to the ????// left of i'th bar including? ????// itself? ????// Right [i] contains height ????// of tallest bar to the right? ????// of ith bar including itself ????// $right[$n]; ????// Initialize result ????$water = 0; ????// Fill left array ????$left[0] = $arr[0]; ????for ($i = 1; $i < $n; $i++) ????$left[$i] = max($left[$i - 1], ????????????????????????$arr[$i]); ????// Fill right array ????$right[$n - 1] = $arr[$n - 1]; ????for ($i = $n - 2; $i >= 0; $i--) ????$right[$i] = max($right[$i + 1],? ???????????????????????????$arr[$i]); ????// Calculate the accumulated ????// water element by element ????// consider the amount of? ????// water on i'th bar, the ????// amount of water accumulated ????// on this particular ????// bar will be equal to min(left[i],? ????// right[i]) - arr[i] . ????for ($i = 0; $i < $n; $i++) ????$water += min($left[$i], $right[$i])? ?????????????????????????????- $arr[$i]; ????return $water; } ????// Driver program ????$arr = array(0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1); ????$n = sizeof($arr); ????echo "Maximum water that can be accumulated is ", ????????findWater($arr, $n); // This code is contributed by ajit ?> ``` **輸出**: ``` Maximum water that can be accumulated is 6 ``` * **復雜度分析**: * **時間復雜度**:`O(n)`。 只需要遍歷數組一次,因此時間復雜度為`O(n)`。 * **空間復雜度**:`O(n)`。 需要兩個額外的數組,每個數組的大小為 n。 * **用于上述解決方案的空間優化:** 代替維護兩個大小為 n 的數組來存儲每個元素的左右最大值,而是維護兩個變量以存儲最大值直到該點。 由于在任何元素處捕獲的水= *min(max_left,max_right)– arr [i]* 。 首先計算從 Alo 和 Ahi 中捕獲的較小元素上的水,然后移動指針,直到 *lo* 沒有越過 *hi* 。 * **實現**: ## C++ ``` // C++ program to find maximum amount of water that can // be trapped within given set of bars. // Space Complexity : O(1) #include <iostream> using namespace std; int findWater(int arr[], int n) { ????// initialize output ????int result = 0; ????// maximum element on left and right ????int left_max = 0, right_max = 0; ????// indices to traverse the array ????int lo = 0, hi = n - 1; ????while (lo <= hi) { ????????if (arr[lo] < arr[hi]) { ????????????if (arr[lo] > left_max) ????????????????// update max in left ????????????????left_max = arr[lo]; ????????????else ????????????????// water on curr element = max - curr ????????????????result += left_max - arr[lo]; ????????????lo++; ????????} ????????else { ????????????if (arr[hi] > right_max) ????????????????// update right maximum ????????????????right_max = arr[hi]; ????????????else ????????????????result += right_max - arr[hi]; ????????????hi--; ????????} ????} ????return result; } int main() { ????int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; ????int n = sizeof(arr) / sizeof(arr[0]); ????cout << "Maximum water that can be accumulated is " ?????????<< findWater(arr, n); } // This code is contributed by Aditi Sharma ``` ## Java ``` // JAVA Code For Trapping Rain Water import java.util.*; class GFG { ????static int findWater(int arr[], int n) ????{ ????????// initialize output ????????int result = 0; ????????// maximum element on left and right ????????int left_max = 0, right_max = 0; ????????// indices to traverse the array ????????int lo = 0, hi = n - 1; ????????while (lo <= hi) { ????????????if (arr[lo] < arr[hi]) { ????????????????if (arr[lo] > left_max) ????????????????????// update max in left ????????????????????left_max = arr[lo]; ????????????????else ????????????????????// water on curr element = ????????????????????// max - curr ????????????????????result += left_max - arr[lo]; ????????????????lo++; ????????????} ????????????else { ????????????????if (arr[hi] > right_max) ????????????????????// update right maximum ????????????????????right_max = arr[hi]; ????????????????else ????????????????????result += right_max - arr[hi]; ????????????????hi--; ????????????} ????????} ????????return result; ????} ????/* Driver program to test above function */ ????public static void main(String[] args) ????{ ????????int arr[] = { 0, 1, 0, 2, 1, 0, 1, ??????????????????????3, 2, 1, 2, 1 }; ????????int n = arr.length; ????????System.out.println("Maximum water that " ???????????????????????????+ "can be accumulated is " ???????????????????????????+ findWater(arr, n)); ????} } // This code is contributed by Arnav Kr. Mandal. ``` ## Python3 ``` # Python program to find # maximum amount of water that can # be trapped within given set of bars. # Space Complexity : O(1) def findWater(arr, n): ????# initialize output ????result = 0 ????# maximum element on left and right ????left_max = 0 ????right_max = 0 ????# indices to traverse the array ????lo = 0 ????hi = n-1 ????while(lo <= hi):? ????????if(arr[lo] < arr[hi]): ????????????if(arr[lo] > left_max): ????????????????# update max in left ????????????????left_max = arr[lo] ????????????else: ????????????????# water on curr element = max - curr ????????????????result += left_max - arr[lo] ????????????lo+= 1 ????????else: ????????????if(arr[hi] > right_max): ????????????????# update right maximum ????????????????right_max = arr[hi] ????????????else: ????????????????result += right_max - arr[hi] ????????????hi-= 1 ????return result # Driver program arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] n = len(arr) print("Maximum water that can be accumulated is ", ????????findWater(arr, n)) # This code is contributed # by Anant Agarwal. ``` ## C# ``` // C# Code For Trapping Rain Water using System; class GFG { ????static int findWater(int[] arr, int n) ????{ ????????// initialize output ????????int result = 0; ????????// maximum element on left and right ????????int left_max = 0, right_max = 0; ????????// indices to traverse the array ????????int lo = 0, hi = n - 1; ????????while (lo <= hi) { ????????????if (arr[lo] < arr[hi]) { ????????????????if (arr[lo] > left_max) ????????????????????// update max in left ????????????????????left_max = arr[lo]; ????????????????else ????????????????????// water on curr element = ????????????????????// max - curr ????????????????????result += left_max - arr[lo]; ????????????????lo++; ????????????} ????????????else { ????????????????if (arr[hi] > right_max) ????????????????????// update right maximum ????????????????????right_max = arr[hi]; ????????????????else ????????????????????result += right_max - arr[hi]; ????????????????hi--; ????????????} ????????} ????????return result; ????} ????// Driver program ????public static void Main() ????{ ????????int[] arr = { 0, 1, 0, 2, 1, 0, 1, ??????????????????????3, 2, 1, 2, 1 }; ????????int result = Trap.findWater(arr, arr.length); ????????System.out.print(" Total trapping water: " + result); ????} } // This code is contributed by vt_m. ``` ## PHP ``` <?php // PHP program to find maximum amount // of water that can be trapped within? // given set of bars. // Method to find maximum amount // of water that can be trapped within? // given set of bars. function findWater($arr, $n) { ????// initialize output ????$result = 0; ????// maximum element on? ????// left and right ????$left_max = 0;? ????$right_max = 0; ????// indices to traverse? ????// the array ????$lo = 0; $hi = $n - 1; ????while($lo <= $hi)? ????{ ????????if($arr[$lo] < $arr[$hi]) ????????{ ????????????if($arr[$lo] > $left_max) ????????????????// update max in left ????????????????$left_max = $arr[$lo]; ????????????else ????????????????// water on curr? ????????????????// element = max - curr ????????????????$result += $left_max - $arr[$lo]; ????????????????$lo++; ????????} ????????else ????????{ ????????????if($arr[$hi] > $right_max) ????????????????// update right maximum ????????????????$right_max = $arr[$hi]; ????????????else ????????????????$result += $right_max - $arr[$hi]; ????????????????$hi--; ????????} ????} ????return $result; } ????// Driver Code ????$arr = array(0, 1, 0, 2, 1, 0,? ?????????????????1, 3, 2, 1, 2, 1); ????$n = count($arr); ????echo "Maximum water that can be accumulated is ", findWater($arr, $n);? // This code is contributed by anuj_67\. ?> ``` **輸出**: ``` Maximum water that can be accumulated is 6 ``` * **復雜度分析**: * **時間復雜度**:`O(n)`。 僅需要遍歷數組一次。 * **輔助空間**:`O(1)`。 由于不需要額外的空間。 * *感謝 Gaurav Ahirwar 和 Aditi Sharma 提出的上述解決方案。* **方法 3:** 這里顯示了另一個有效的解決方案。 * **方法**:這里的概念是,如果右側有較大的墻,則可以保留與左側較小的墻相同高度的水。 如果右側沒有較大的墻,則從左側開始。 現在左側必須有一堵更大的墻。 讓我們舉個例子,如果高度為{…。,3,2,1,4,....},那么這里 3 和 4 是邊界,高度 2 和 1 被淹沒并且不能充當邊界。 因此,在數組的其余部分中存在更高或相等長度的邊界時,在任何點或索引處都知道前一個邊界就足夠了。 如果不是,則向后遍歷數組,現在必須在左側留一堵更大的墻。 * **算法**: * 從索引 0 循環到給定數組的末尾。 * 如果遇到大于或等于前一個墻的墻,請在稱為 prev_index 的 var 中記錄該墻的索引。 * 繼續將前一堵墻的高度減去當前(i <sup>至</sup>)墻的高度添加到可變水量中。 * 有一個臨時變量,該變量存儲與水相同的值。 * 如果沒有發現大于或等于前一個墻的墻,則退出。 * 如果輸入數組的大小為 prev_index <,則從水中減去 temp 變量,然后從輸入數組的末尾循環到 prev_index,并找到大于或等于前一面的墻(在這種情況下,從后向后的最后一面墻) )。 * **實現**: ## Java ``` // Java implementation of the approach class GFG { ????// Function to return the maximum ????// water that can be stored ????public static int maxWater(int arr[], int n) ????{ ????????int size = n - 1; ????????// Let the first element be stored as ????????// previous, we shall loop from index 1 ????????int prev = arr[0]; ????????// To store previous wall's index ????????int prev_index = 0; ????????int water = 0; ????????// To store the water until a larger wall ????????// is found, if there are no larger walls ????????// then delete temp value from water ????????int temp = 0; ????????for (int i = 1; i <= size; i++) { ????????????// If the current wall is taller than ????????????// the previous wall then make current ????????????// wall as the previous wall and its ????????????// index as previous wall's index ????????????// for the subsequent loops ????????????if (arr[i] >= prev) { ????????????????prev = arr[i]; ????????????????prev_index = i; ????????????????// Because larger or same height wall is found ????????????????temp = 0; ????????????} ????????????else { ????????????????// Since current wall is shorter than ????????????????// the previous, we subtract previous ????????????????// wall's height from the current wall's ????????????????// height and add it to the water ????????????????water += prev - arr[i]; ????????????????// Store the same value in temp as well ????????????????// If we dont find any larger wall then ????????????????// we will subtract temp from water ????????????????temp += prev - arr[i]; ????????????} ????????} ????????// If the last wall was larger than or equal ????????// to the previous wall then prev_index would ????????// be equal to size of the array (last element) ????????// If we didn't find a wall greater than or equal ????????// to the previous wall from the left then ????????// prev_index must be less than the index ????????// of the last element ????????if (prev_index < size) { ????????????// Temp would've stored the water collected ????????????// from previous largest wall till the end ????????????// of array if no larger wall was found then ????????????// it has excess water and remove that ????????????// from 'water' var ????????????water -= temp; ????????????// We start from the end of the array, so previous ????????????// should be assigned to the last element ????????????prev = arr[size]; ????????????// Loop from the end of array up to the 'previous index' ????????????// which would contain the "largest wall from the left" ????????????for (int i = size; i >= prev_index; i--) { ????????????????// Right end wall will be definitely smaller ????????????????// than the 'previous index' wall ????????????????if (arr[i] >= prev) { ????????????????????prev = arr[i]; ????????????????} ????????????????else { ????????????????????water += prev - arr[i]; ????????????????} ????????????} ????????} ????????// Return the maximum water ????????return water; ????} ????// Driver code ????public static void main(String[] args) ????{ ????????int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; ????????int n = arr.length; ????????System.out.print(maxWater(arr, n)); ????} } ``` ## Python3 ``` # Pythpn3 implementation of the approach # Function to return the maximum # water that can be stored def maxWater(arr, n): ????size = n - 1 ????# Let the first element be stored as ????# previous, we shall loop from index 1 ????prev = arr[0] ????# To store previous wall's index ????prev_index = 0 ????water = 0 ????# To store the water until a larger wall ????# is found, if there are no larger walls ????# then delete temp value from water ????temp = 0 ????for i in range(1, size + 1): ????????# If the current wall is taller than ????????# the previous wall then make current ????????# wall as the previous wall and its ????????# index as previous wall's index ????????# for the subsequent loops ????????if (arr[i] >= prev): ????????????prev = arr[i] ????????????prev_index = i ????????????# Because larger or same height wall is found ????????????temp = 0 ????????else: ????????????# Since current wall is shorter than ????????????# the previous, we subtract previous ????????????# wall's height from the current wall's ????????????# height and add it to the water ????????????water += prev - arr[i] ????????????# Store the same value in temp as well ????????????# If we dont find any larger wall then ????????????# we will subtract temp from water ????????????temp += prev - arr[i] ????# If the last wall was larger than or equal ????# to the previous wall then prev_index would ????# be equal to size of the array (last element) ????# If we didn't find a wall greater than or equal ????# to the previous wall from the left then ????# prev_index must be less than the index ????# of the last element ????if (prev_index < size): ????????# Temp would've stored the water collected ????????# from previous largest wall till the end ????????# of array if no larger wall was found then ????????# it has excess water and remove that ????????# from 'water' var ????????water -= temp ????????# We start from the end of the array, so previous ????????# should be assigned to the last element ????????prev = arr[size] ????????# Loop from the end of array up to the 'previous index' ????????# which would contain the "largest wall from the left" ????????for i in range(size, prev_index - 1, -1): ????????????# Right end wall will be definitely smaller ????????????# than the 'previous index' wall ????????????if (arr[i] >= prev): ????????????????prev = arr[i] ????????????else: ????????????????water += prev - arr[i] ????# Return the maximum water ????return water # Driver code arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] n = len(arr) print(maxWater(arr, n)) # This code is contributed by Mohit Kumar ``` **輸出**: ``` 6 ``` * **復雜度分析**: * **時間復雜度**:`O(n)`。 由于僅需要遍歷數組一次。 * **輔助空間**:`O(1)`。 由于不需要額外的空間。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看