The problem is introduced and proven (manually) here: https://leimao.github.io/blog/Proof-Container-With-Most-Water-Problem/
We’ll do the proof in Dafny.
method maxArea(height: array?<int>) returns (vol: int, maxVol: int)
requires height != null && 0 < height.Length
ensures maxVol >= vol
{
var i := 0;
var j := height.Length - 1;
maxVol := 0;
vol := 0;
while i < j
invariant i <= j && j < height.Length && maxVol >= vol
{
if height[i] < height[j]
{
vol := (j - i) * height[i];
i := i + 1;
}
else
{
vol := (j - i) * height[j];
j := j - 1;
}
if vol > maxVol {
maxVol := vol;
}
}
}
Namely, the invariant holds for every iteration, whenever
or
. Thus, at the end of the iterations,
will contain the largest volume.
Bonus: If you compare Dafny's source code to the one on the blog post you will notice they are very similar, which is what makes Dafny super cool. 🙂