The Sliding Window Technique
Here’s a seemingly simple problem that has nothing to do with substring search. Say we have the array [3, 2, 7, 4, 6, 3, 5, 8], and we want to find the greatest contiguous four integers that yield the greatest sum when added together. Here’s what I mean.
The first four integers of the array 3, 2, 7, 4 are contiguous, meaning they’re all in a row. And when we add them together, we get a sum of 16. Cool.
The problem I’m proposing is to find the set of four contiguous integers that will yield the greatest sum in the array. For example, there’s another set of four contiguous numbers—7, 4, 6, 3—that add up to 20. Is this the greatest sum we can get, though? Let’s devise an algorithm to figure this out.
One approach we ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access