Problem · Array

Maximum Stock Profit with At Most Two Transactions

Learn this problem
MediumMicrosoft logoMicrosoftFULLTIMEONSITE INTERVIEW
See Microsoft hiring insights

Problem statement

You are given an array prices, where prices[i] is the price of one stock on day i. Return the maximum profit you can earn by completing at most two transactions.

A transaction consists of buying one share and selling that share on a later day. You may hold at most one share at a time, so a second transaction can begin only after the first transaction has been sold. You may also complete fewer than two transactions.

Function

maxProfitAtMostTwo(prices: int[]) → int

Examples

Example 1

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

Buy at 0 and sell at 3, then buy at 1 and sell at 4. The total profit is 3 + 3 = 6.

Example 2

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

One transaction from price 1 to price 5 earns the maximum profit of 4.

Example 3

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

No later price exceeds an earlier price, so the best choice is to make no transaction.

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^5
  • A buy must occur before its matching sell.
  • Transactions may not overlap.

More Microsoft problems

drafts saved locally
public int maxProfitAtMostTwo(int[] prices) {
  // write your code here
}
prices[3,3,5,0,0,3,1,4]
expected6
checking account