KatInterview

Calculate Maximum Single-Trade Return

Arrays & HashingAuto-graded · 19 test cases
EasyAuto-gradedArrays & Hashingarraysdynamic-programminggreedy-intervals

Last updated

Find the maximum non-negative profit from purchasing an asset on one day and selling it on a subsequent day.

You are given a list of integers prices, where prices[i] represents the price of a given asset on day i.

Determine the maximum profit achievable by completing at most one purchase and one sale of the asset. You must buy the asset on a given day before selling it on a later day. If no profitable trade can be executed, return 0.

Constraints

  • 1 <= 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

Example 4

Input: max_profit([2, 1, 4, 1, 7])

Output: 6

Hints

Hint 1

If you choose to complete a trade on day j, what would be the optimal day i (where i < j) to purchase the asset?

Hint 2

Can you maintain the minimum price encountered so far as you iterate through the list from left to right?

Hint 3

Remember that you can execute zero transactions if prices continuously fall, so the baseline profit is always 0.