KatInterview

Maximum Gain from Single Asset Trade

Arrays & HashingAuto-graded · 22 test cases
EasyAuto-gradedArrays & Hashingarraysgreedyprefix-minimum

Last updated

Determine the maximum possible gain achieved by completing at most one purchase and sale transaction over a sequence of prices.

Given an array of non-negative integers prices representing the value of an asset on successive days, determine the maximum profit achievable by buying on one day and selling on a subsequent day.

You may complete at most one buy and one sell transaction. You cannot sell an asset before buying it. If no positive profit can be made (for instance, if prices strictly decrease or remain constant), return 0.

Constraints

  • 1 <= len(prices) <= 100,000
  • 0 <= prices[i] <= 1,000,000,000
  • Time complexity must be $O(n)$ where $n$ is the number of elements in prices.
  • Auxiliary space complexity must be $O(1)$.

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

Hints

Hint 1

To maximize profit when selling on day j, which earlier day should you select as the buying day?

Hint 2

Try maintaining the smallest price seen so far as you iterate through the sequence.

Hint 3

Can you update the overall maximum profit encountered at each step using only $O(1)$ additional storage?