FastPrepMaximum Profit with Exactly One Stock Transaction

Maximum Profit with Exactly One Stock Transaction

Retool logoRetool● EasyFULLTIMENEW GRADPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

Given daily stock prices, choose exactly one buy day and one later sell day. Return the greatest possible profit sellPrice - buyPrice.

You must complete the transaction even when every choice loses money, so the answer may be negative.

Function

maxProfitExactlyOne(prices: int[]) → int

Examples

Example 1

prices = [7,1,5,3,6,4]return = 5

Buy at 1 and sell later at 6.

Example 2

prices = [7,6,4,3,1]return = -1

The least costly required trade buys at 7? No: buying at 4 and selling at 3, or buying at 3 and selling at 1, loses at least 1; the best legal loss is -1.

Example 3

prices = [3,3]return = 0

Buying and selling on the two distinct days produces zero profit.

Constraints

  • 2 <= prices.length <= 100000.
  • 0 <= prices[i] <= 1000000.
  • The answer fits in a signed 32-bit integer.

More Retool problems

See Retool hiring insights
public int maxProfitExactlyOne(int[] prices) {
    // write your code here
}
prices[7,1,5,3,6,4]
expected5
Checking account…