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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code