Maximum Profit with Exactly One Stock Transaction
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[]) → intExamples
Example 1
prices = [7,1,5,3,6,4]return = 5Buy at 1 and sell later at 6.
Example 2
prices = [7,6,4,3,1]return = -1The 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 = 0Buying 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.