KatInterview

Determine Highest Single Transaction Stock Profit

Arrays & HashingAuto-graded · 23 test cases
EasyAuto-gradedArrays & Hashingarraysgreedydynamic-programming

Last updated

Find the maximum gain possible from buying and selling a stock once, given a sequence of daily values.

You are given an array of daily stock valuations prices, where prices[i] represents the valuation on day i.

Calculate the maximum possible profit achievable by selecting a single day to purchase the stock and a subsequent day to sell it.

If no positive profit can be made (for example, if stock values only decrease or remain constant), return 0.

Constraints

  • 0 <= len(prices) <= 10^5
  • 0 <= prices[i] <= 10^4

Examples

Example 1

Input: max_profit([7, 1, 5, 3, 6, 4])

Output: 5

Example 2

Input: max_profit([7, 6, 4, 3, 1])

Output: 0

Example 3

Input: max_profit([1, 2])

Output: 1

Hints

Hint 1

Think about what price you would want to buy at if you decided to sell on day i.

Hint 2

As you iterate through the prices, keep track of the lowest price observed so far.

Hint 3

The potential profit on day i is simply prices[i] minus the minimum price seen prior to day i.