Problem · Array

Maximum Stock Profit with Transaction Limits

Learn this problem
MediumMeta logoMetaFULLTIMEONSITE INTERVIEW
See Meta hiring insights

Problem statement

Given daily stock prices prices and a transaction mode transactionLimit, return the maximum profit you can earn.

  • When transactionLimit == 1, complete at most one buy-then-sell transaction.
  • When transactionLimit == -1, complete any number of nonoverlapping buy-then-sell transactions.

You may hold at most one share at a time. A sale must occur on a day after its matching purchase. You may always choose not to trade, so the answer is never negative.

Function

maxStockProfit(prices: int[], transactionLimit: int) → long

Examples

Example 1

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

Take the rises from 1 to 5 and from 3 to 6, for total profit 4 + 3 = 7.

Example 2

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

The best single transaction buys at 1 and sells later at 6.

Example 3

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

No later price exceeds an earlier purchase price, so skipping all trades is optimal.

Constraints

  • 0 <= prices.length <= 200000.
  • 0 <= prices[i] <= 10^9.
  • transactionLimit is either 1 or -1.
  • The answer fits a signed 64-bit integer.

More Meta problems

drafts saved locally
public long maxStockProfit(int[] prices, int transactionLimit) {
    // Write your code here.
}
prices[7,1,5,3,6,4]
transactionLimit-1
expected7
checking account