Last active
December 20, 2024 07:37
-
-
Save mrmu/3b44267cb6621f446a48d5538dbc2015 to your computer and use it in GitHub Desktop.
Leetcode: php 給一個陣列,裡面每個值代表容器兩旁的高度,要計算使用哪兩個高度,可以取得最大面積,並且顯示面積結果。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| function maxArea($height) { | |
| $result = 0; | |
| // 第一個高度的位置 | |
| for ($i = 0; $i < sizeof($height); $i++) { | |
| // 第二個高度的位置 | |
| for ($j = 1; $j < sizeof($height); $j++) { | |
| // 相同高度不用和自己比較 | |
| if ($i === $j) { | |
| continue; | |
| } | |
| // 第二個高度不用再跟前面位置的高度比較 | |
| if (($j - $i) < 0) { | |
| continue; | |
| } | |
| // 取得第一個高度 | |
| $a = $height[$i]; | |
| // 取得第二個高度 | |
| $b = $height[$j]; | |
| // 水裝滿只能達到較低的那個高度 | |
| $lh = min($a, $b); | |
| // 計算面積,較低的高度* X軸的距離 (每個高度間隔為1) | |
| $result = max($result, ($lh * ($j-$i) )); | |
| // 每次比較的結果 | |
| echo $a . ':' .$b . '-' .$lh . 'x' . '(' . $j .'-'. $i.')' . '=' . ($lh * ($j-$i) ) . "\n"; | |
| } | |
| } | |
| return $result; | |
| } | |
| // 答案應為49,在8~7之間,較低高度為 7 * X軸距離為 7 = 49 | |
| echo 'Ans: ' . maxArea([1,8,6,2,5,4,8,3,7]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment