Maximum Profitable Triplets With Increasing Prices II - Problem

You're running an online marketplace and need to maximize profit by selecting three items with strictly increasing prices. Given two arrays:

  • prices[i] - the price of the ith item
  • profits[i] - the profit from selling the ith item

Find three items at indices i < j < k where prices[i] < prices[j] < prices[k] and maximize profits[i] + profits[j] + profits[k].

Goal: Return the maximum possible profit from such a triplet, or -1 if no valid triplet exists.

Example: If prices = [10, 20, 30, 40] and profits = [20, 30, 40, 50], the answer is 120 (selecting all items gives maximum profit).

Input & Output

example_1.py โ€” Basic Valid Triplet
$ Input: prices = [10, 20, 30, 40]\nprofits = [20, 30, 40, 50]
โ€บ Output: 120
๐Ÿ’ก Note: We can select all items: indices (0,1,2) give profit 20+30+40=90, indices (0,1,3) give 20+30+50=100, indices (0,2,3) give 20+40+50=110, indices (1,2,3) give 30+40+50=120. The maximum is 120.
example_2.py โ€” No Valid Triplet
$ Input: prices = [40, 30, 20, 10]\nprofits = [50, 40, 30, 20]
โ€บ Output: -1
๐Ÿ’ก Note: Prices are in decreasing order, so no triplet with increasing prices exists.
example_3.py โ€” Mixed Case
$ Input: prices = [5, 10, 15, 8, 12]\nprofits = [100, 20, 30, 40, 50]
โ€บ Output: 190
๐Ÿ’ก Note: Best triplet is indices (0,3,4) with prices [5,8,12] and profits 100+40+50=190.

Constraints

  • 3 โ‰ค n โ‰ค 105
  • 1 โ‰ค prices[i] โ‰ค 106
  • 1 โ‰ค profits[i] โ‰ค 106
  • prices[i] and profits[i] can be independent values

Visualization

Tap to expand
Investment Portfolio Optimization$10Profit: $20Stock A$20Profit: $30Stock B$30Profit: $40Stock C$40Profit: $50Stock DOptimal Strategy: Binary Indexed TreeFor each middle stock (B), efficiently find:Left Range QueryMax profit from stockswith price < $20Result: $20 (Stock A)Right Range QueryMax profit from stockswith price > $20Result: $50 (Stock D)Total Maximum Profit: $20 + $30 + $50 = $100Time Complexity: O(n log n) using coordinate compression + BIT
Understanding the Visualization
1
Scan Portfolio
Look through all available stocks in chronological order
2
Track Price Ranges
For each stock, know the best profits available from cheaper and more expensive stocks
3
Optimal Selection
Pick the combination that gives maximum total profit while maintaining price order
4
Efficient Lookup
Use advanced data structures to avoid checking every combination manually
Key Takeaway
๐ŸŽฏ Key Insight: Use Binary Indexed Tree to efficiently query maximum profits in price ranges, avoiding the need to check all possible triplet combinations manually.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
38.0K Views
High Frequency
~25 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen