Greedy Algorithms8 sections · 316 units
Open in Course

Problem - Best Time to Buy and Sell Stock

One transaction

Given an array where prices[i]prices[i] is the stock price on day ii, find the maximum profit from one buy and one sell.

You must buy before you sell.

For example, prices=[7,1,5,3,6,4]prices = [7,1,5,3,6,4] gives profit 55 (buy at 11, sell at 66).

This looks like a search problem, but you can solve it greedily.

Think about what you need to track as you scan through prices. Constraint: n105n \le 10^5. Checking all O(n2)O(n^2) time using O(1)O(1) space buy-sell pairs times out.