Maximum Stock Profit with Transaction Limits
Updated
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) → longExamples
Example 1
prices = [7,1,5,3,6,4]transactionLimit = -1return = 7Take 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 = 5The best single transaction buys at 1 and sells later at 6.
Example 3
prices = [7,6,4,3,1]transactionLimit = -1return = 0No later price exceeds an earlier purchase price, so skipping all trades is optimal.
Constraints
0 <= prices.length <= 200000.0 <= prices[i] <= 10^9.transactionLimitis either1or-1.- The answer fits a signed 64-bit integer.
More Meta Onsite Interview questions
- Multi-Head Attention Forward PassPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Run-Length Encoded Vector Dot ProductPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Mutual-Friend RecommendationsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Deterministic K-Means AssignmentsPHONE SCREEN · ONSITE INTERVIEW · Seen Sep 2026
- Linear Layer Forward and Backward PassesONSITE INTERVIEW · Seen Sep 2026
- Reservoir Sampling with Recorded DrawsONSITE INTERVIEW · Seen Sep 2026
- Stochastic Gradient Descent with MomentumONSITE INTERVIEW · Seen Sep 2026
- Top K Largest Values with a HeapONSITE INTERVIEW · Seen Sep 2026
- Partition a Card Deck into FifteensONSITE INTERVIEW · Seen Sep 2026
- Insert into a Sorted Circular ListONSITE INTERVIEW · Seen Aug 2026
Similar questions at other companies
- Best Time to Buy and Sell Stock IIKotak Mahindra Bank · ONSITE INTERVIEWKotak Mahindra Bank interview questions
- Maximum Stock Profit with Unlimited TransactionsSalesforce · ONSITE INTERVIEWSalesforce interview questions
- Jump Game IIOracle · ONSITE INTERVIEWOracle interview questions
- Jump Game IITripjack · ONSITE INTERVIEWTripjack interview questions
- First Five Increasing Temperature RangesAmazon · ONSITE INTERVIEW
- Return a Minimum-Coin Change BreakdownDatadog · PHONE SCREEN · ONSITE INTERVIEWDatadog interview questions
- Most Transactions Kept Without Going NegativeDocuSign · ONSITE INTERVIEWDocuSign interview questions
- Best Time to Buy and Sell Stock IIHeadlands Technologies · ONSITE INTERVIEWHeadlands Technologies interview questions
- Fewest Jumps to the Last IndexC3.ai · ONSITE INTERVIEWC3.ai interview questions
- Jump GameBloomberg LP · ONSITE INTERVIEWBloomberg LP interview questions