Stock Profit with at Most Two Transactions
Updated
Problem statement
Given daily stock prices, return the maximum profit from at most two buy-then-sell transactions. A buy must happen before its matching sell, and the first sale must happen before the second buy. Hold at most one share at a time.
You may complete zero or one transaction when that is better. There are no fees or cooldowns.
Function
maxProfitAtMostTwo(prices: int[]) → intExamples
Example 1
prices = [3,3,5,0,3,1,4]return = 6Buy 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 = 4One transaction from price 1 to price 5 earns the maximum profit of 4.
Example 3
prices = [7,6,4,3,1]return = 0No later price exceeds an earlier price, so the best choice is to make no transaction.
Constraints
1 <= prices.length <= 10^50 <= prices[i] <= 10^5- A buy must occur before its matching sell.
- Transactions may not overlap.
More Expedia Onsite Interview questions
- Scramble StringONSITE INTERVIEW · Seen Sep 2026
- Smallest Sufficient TeamONSITE INTERVIEW · Seen Sep 2026
- Check Anagram Pairs Index by IndexONSITE INTERVIEW · Seen Oct 2025
- Fresh Oranges Left After Rotting StopsONSITE INTERVIEW · Seen Oct 2025
- Longest Increasing SubsequenceONSITE INTERVIEW · Seen Oct 2025
- Lowest Common Ancestor with Repeated and Missing ValuesONSITE INTERVIEW · Seen Oct 2025
- Shortest Substring with Exactly K OnesONSITE INTERVIEW · Seen Oct 2025
- Middle Element of a Linked ListONSITE INTERVIEW · Seen Nov 2024
- Minimum in a Rotated Sorted ArrayONSITE INTERVIEW · Seen Sep 2024
- Mirror Image Binary TreesONSITE INTERVIEW · Seen Sep 2024
Similar questions at other companies
- Count Subsets With a Target SumSafe Security · ONSITE INTERVIEW
- 0/1 Knapsack with Weight and Volume LimitsGoogle · ONSITE INTERVIEWGoogle interview questions
- Maximum Subarray Sum with One DeletionOracle · ONSITE INTERVIEWOracle interview questions
- Best Time to Buy and Sell Stock IIKotak Mahindra Bank · ONSITE INTERVIEWKotak Mahindra Bank interview questions
- Coin ChangeMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Word BreakAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Maximum SubarrayUpstart · ONSITE INTERVIEWUpstart interview questions
- Maximum Product SubarrayHartford Financial Services · ONSITE INTERVIEWHartford Financial Services interview questions
- Word BreakMoveworks · ONSITE INTERVIEWMoveworks interview questions
- Maximum Value from Circular HousesDigitalOcean · ONSITE INTERVIEWDigitalOcean interview questions
Interview reports that mention this question
Expedia interview experiences
- Expedia Intern Final Round in 2021: 28 Experiences (Part 4 of 6)
- Expedia Intern Finals Before 2020: 14 Experiences (Part 6 of 6)
- Expedia Intern Final Round in 2020: 24 Experiences (Part 5 of 6)
- Expedia Intern Final Round in 2022: 15 Experiences (Part 3 of 6)
- Expedia Intern Final Round in 2023: 17 Experiences (Part 2 of 6)