Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode题解:11. 盛最多水的容器,双循环暴力法,JavaScript,详细注释 #135

Open
chencl1986 opened this issue Aug 20, 2020 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:https://leetcode-cn.com/problems/container-with-most-water/

解题思路:

  1. 该题题意为,查找所有两个柱子之间组成的长方形面积中的最大值。
  2. 使用双循环遍历所有的柱子,计算每两个柱子组成的长方形面积。
  3. 将当前计算的面积,与上一次循环中缓存的面积相比,取最大值进行缓存。
  4. 当完成所有元素的遍历后,最终缓存的值即为可容纳水的最大值。
/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function (height) {
  let result = 0;

  // 利用双循环遍历数组(即每一根柱子),保证遍历到每一个值
  for (let i = 0; i < height.length - 1; i++) {
    for (let j = 0; j < height.length; j++) {
      // 容积能装的水量,等于两个柱子中最低的柱子高度,乘以两个柱子之间的距离
      // 计算两个柱子的最小高度
      const minHeight = Math.min(height[i], height[j]);
      // 用最小高度乘以柱子的距离,即为当前两根柱子所围面积
      const area = minHeight * (j - i);
      // 对比当前值和缓存的面积,取最大值保存,当完成循环时,result中保存的就是最大值。
      result = Math.max(area, result);
    }
  }

  return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant