Little Puzzlers–Largest Puddle on a Bar Chart

I like to keep my brain sharp by working on programming puzzlers. On off weeks I'm going to start posting programming puzzlers I've collected over the years. Hopefully you'll find them as entertaining as I do.

This is perhaps one of the more fun problems I’ve had to solve in an evaluation situation before.  I’m not claiming I have the optimal answer, so I’ll be curious to see what you all come up with as well!

The Problem:

Given an array of int that represents the height of bars in a bar chart, calculate the size of the largest puddle that would form if water were poured over the top of the graph. 

You may assume the following:

  • All bars have a width of 1
  • There is no extra space between adjacent bars.
  • There are no negative bars
  • The edges of the bar chart are an implicit “zero” height.

Example:

Assume you had the following array:

var bars = new [] { 10, 20, 80, 70, 60, 90, 40, 30, 40, 70 };

We would have the following bar chart with the indicated puddles forming on top:

GraphPool

Note that no water pools on the left side because there isn’t a left “wall” to hold it in.

So in this example, two pools would form: one from the 80-90 bars that hold 30 units of water, and one from the 90 bar to the 70 bar that holds 100 units of water.  Thus the largest pool size would have an area of 100.

Spoiler Alert!

Fair Warning: there may be discussion of the problem and potential solutions posted in the comments below.

This article is part of the GWB Archives. Original Author: James Michael Hare

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.