Maximum Profitable Triplets With Increasing Prices I - Problem

You're running an online store with n items, each having a specific price and potential profit. Your goal is to select exactly three items that will maximize your total profit, but there's a catch!

The three items you pick must satisfy a strict ordering condition: if you select items at indices i, j, and k, then:

  • i < j < k (indices must be in increasing order)
  • prices[i] < prices[j] < prices[k] (prices must also be strictly increasing)

If you successfully pick three items meeting these conditions, your total profit will be profits[i] + profits[j] + profits[k].

Your task: Return the maximum profit you can achieve by selecting three items, or -1 if no valid triplet exists.

Input & Output

example_1.py โ€” Basic Case
$ Input: prices = [10, 20, 30], profits = [5, 10, 15]
โ€บ Output: 30
๐Ÿ’ก Note: We can select all three items (indices 0, 1, 2) since prices are strictly increasing (10 < 20 < 30). Total profit = 5 + 10 + 15 = 30.
example_2.py โ€” No Valid Triplet
$ Input: prices = [30, 20, 10], profits = [15, 10, 5]
โ€บ Output: -1
๐Ÿ’ก Note: No valid triplet exists because prices are in decreasing order. We need strictly increasing prices to form a valid triplet.
example_3.py โ€” Multiple Valid Triplets
$ Input: prices = [1, 3, 2, 4, 5], profits = [1, 5, 3, 6, 7]
โ€บ Output: 18
๐Ÿ’ก Note: Best triplet is at indices (0, 3, 4): prices [1, 4, 5] with profits [1, 6, 7]. Total profit = 1 + 6 + 7 = 14. Actually, better is indices (1, 3, 4): prices [3, 4, 5] with profits [5, 6, 7] = 18.

Constraints

  • 3 โ‰ค n โ‰ค 2000
  • 1 โ‰ค prices[i] โ‰ค 5000
  • 1 โ‰ค profits[i] โ‰ค 5000
  • prices[i] values may have duplicates
  • We need strictly increasing prices: prices[i] < prices[j] < prices[k]

Visualization

Tap to expand
Investment Portfolio StrategyStock APrice: $10Profit: $51stStock BPrice: $20Profit: $102ndStock CPrice: $30Profit: $153rdTotal Portfolio$10 < $20 < $30 โœ“Returns: $5 + $10 + $15 = $30
Understanding the Visualization
1
Choose First Stock
Select a stock with lower price as the foundation
2
Choose Second Stock
Pick a middle-priced stock that costs more than the first
3
Choose Third Stock
Select the highest-priced stock to complete the ascending sequence
4
Calculate Returns
Sum up profits from all three stocks for total portfolio return
Key Takeaway
๐ŸŽฏ Key Insight: For each middle element, we only need to track the maximum profit from cheaper items on the left and more expensive items on the right, then combine them optimally.
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
28.4K Views
Medium-High Frequency
~25 min Avg. Time
856 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