FastPrepMaximum Profit with Exactly Two Stock Transactions

Maximum Profit with Exactly Two Stock Transactions

Retool logoRetool● MediumFULLTIMENEW GRADPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

Given daily stock prices, complete exactly two non-overlapping transactions. Each transaction buys once and sells on a later day, and the first sale must occur before the second purchase.

Return the maximum sum of the two profits. Both transactions are required, so either one may lose money.

Function

maxProfitExactlyTwo(prices: int[]) → int

Examples

Example 1

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

Trade from 3 to 5, then from 0 to 4.

Example 2

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

Two required adjacent one-point losses are optimal.

Example 3

prices = [1,2,3,4]return = 2

Use two one-point gains: 1 to 2 and 3 to 4.

Constraints

  • 4 <= 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 maxProfitExactlyTwo(int[] prices) {
    // write your code here
}
prices[3,3,5,0,0,3,1,4]
expected6
Checking account…