barrettruth.com/posts/two-pointers.html

100 lines
3.6 KiB
HTML

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="../styles/common.css" />
<link rel="stylesheet" href="../styles/post.css" />
<link rel="icon" type="image/webp" href="../public/logo.webp" />
<link href="../public/prism/prism.css" rel="stylesheet" />
<link href="../public/prism/prism-theme.css" rel="stylesheet" />
<script defer src="../public/prism/prism.js"></script>
<link rel="stylesheet" href="../public/katex/katex.css" />
<script defer src="../public/katex/katex.js"></script>
<script
defer
src="../public/katex/katex-render.js"
onload="renderMathInElement(document.body);"
></script>
<title>Barrett Ruth</title>
</head>
<body class="graph">
<header>
<a
href="/"
style="text-decoration: none; color: inherit"
onclick="goHome(event)"
>
<div class="terminal-container">
<span class="terminal-prompt">barrett@ruth:~$ /algorithms</span>
<span class="terminal-cursor"></span>
</div>
</a>
</header>
<main class="main">
<div class="post-container">
<header class="post-header">
<h1 class="post-title">Two Pointers</h1>
<p class="post-meta">
<time datetime="2024-06-16">16/06/2024</time>
</p>
</header>
<article class="post-article">
<h2>technique overview</h2>
<h3>
<a
target="blank"
href="https://leetcode.com/problems/container-with-most-water/"
>container with most water</a
>
</h3>
<p>Sometimes, the mathematical solution is the simplest.</p>
<p>
The area of a container bounded by the ground and its columns at
positions \((l, r)\) is: \[ \text{area} = \text{width} \cdot
\text{length} = (r - l) \cdot \min\{height[l], height[r]\} \]
</p>
<p>
At its core, this is a maximization problem: maximize the contained
area. \[ \max\{(r - l) \cdot \min\{height[l], height[r]\}\} \]
</p>
<p>
Given a new column position \(l_0 < l\) or \(r_0 < r\), the
contained area can only increase if the height of the corresponding
column increases.
</p>
<!-- TODO: add footnote -->
<p>
The following correct solution surveys all containers, initialized
with the widest columns positions, that are valid candidates for a
potentially new largest area. A running maximizum, the answer, is
maintained.
</p>
<div class="post-code">
<pre><code class="language-python">def maxArea(height: list[int]) -> int:
area = 0
l, r = 0, len(height) - 1
while l < r:
width, min_height = r - l, min(height[l], height[r])
area = max(area, width * min_height)
while l < r and height[l] <= min_height:
l += 1
while l < r and height[r] <= min_height:
r -= 1
return area</code></pre>
</div>
<!-- <h3> -->
<!-- <a -->
<!-- target="blank" -->
<!-- href="https://leetcode.com/problems/boats-to-save-people/" -->
<!-- >boats to save people</a -->
<!-- > -->
<!-- </h3> -->
</article>
</div>
</main>
<script src="../scripts/common.js"></script>
<script src="../scripts/post.js"></script>
</body>
</html>