Best Time to Buy and Sell Stock

This problem gets grouped with sliding window in every study guide. But is that label actually correct? Before we answer that, let us figure out what the problem even needs. Given an array of stock prices where prices[i] is the price on day i, find the maximum profit from buying on one day and selling on a later day. If no profit is possible, return 0.

The straightforward approach: check every possible buy-sell pair. For each potential sell day, scan every prior day to see what the profit would have been. Sounds reasonable. What does the brute force look like? Let us try it on a real input -- 715364 -- and see how the work feels.

Check Every Pair

Day 0Day 1Day 2Day 3Day 4Day 5715364
7
0
1
1
5
2
3
3
6
4
4
5

Selling on Day 1 (price=1). Tap each prior buy day to check the profit.

Total checks0