Problem Description
Given two 0-indexed arrays prices and profits where the iᵗʰ item costs prices[i] and yields a profit of profits[i], pick three items with indices i, j, k (with i < j < k) satisfying prices[i] < prices[j] < prices[k]. The goal is to maximize the total profit: profits[i] + profits[j] + profits[k]. If no valid triplet exists, return -1.
Key Insights
- For each candidate middle item j, we independently need:
- A left candidate i (with i < j) having the largest profit among those with prices[i] < prices[j].
- A right candidate k (with k > j) having the largest profit among those with prices[k] > prices[j].
- The sum is linear so the problem reduces to precomputing for every index j the optimal left and right profits.
- Because prices are bounded (up to 5000), Binary Indexed Trees (BIT) or Segment Trees can be used to quickly query maximum profits over a range of prices.
- The left side can be processed in a forward pass using a standard BIT that supports range maximum queries.
- The right side is processed in a backward pass. By mapping each price p to a reversed index (maxPrice – p + 1), we can use a BIT to quickly query the maximum profit among items with higher price.
Space and Time Complexity
Time Complexity: O(n log M), where M is the maximum price (<= 5000) Space Complexity: O(M + n)
Solution
We solve the problem in two passes:
- During a left-to-right pass, for each index j, we use a BIT (keyed by price) to query the maximum profit among all indices i < j with prices[i] < prices[j]. This value is stored in leftBest[j].
- During a right-to-left pass, we use a modified BIT that works on reversed price indices. For each index j, we query for the maximum profit among indices k > j having prices[k] > prices[j] and store the result in rightBest[j].
- Finally, for each index j that qualifies (both leftBest[j] and rightBest[j] are valid), we compute the sum leftBest[j] + profits[j] + rightBest[j] and track the maximum sum.
- If no valid triplet exists, return -1.
Key data structures:
- Two Binary Indexed Trees (one for each pass) for efficient range maximum queries.
- The BIT update and query operations run in O(log M) time.
This approach ensures we meet the constraint requirements even for n up to 50000.