Maximum Profitable Triplets With Increasing Prices II - Problem

You are given two 0-indexed arrays prices and profits of length n. There are n items in a store where the ith item has a price of prices[i] and a profit of profits[i].

We need to pick exactly three items with the following condition: prices[i] < prices[j] < prices[k] where i < j < k.

If we pick items with indices i, j, and k satisfying the above condition, the profit would be profits[i] + profits[j] + profits[k].

Return the maximum profit we can get, or -1 if it's not possible to pick three items with the given condition.

Input & Output

Example 1 — Basic Valid Triplet
$ Input: prices = [10,20,30,40], profits = [20,30,40,50]
Output: 120
💡 Note: Pick indices (0,1,2): prices 10 < 20 < 30, profits 20+30+40 = 90. Pick indices (0,1,3): prices 10 < 20 < 40, profits 20+30+50 = 100. Pick indices (0,2,3): prices 10 < 30 < 40, profits 20+40+50 = 110. Pick indices (1,2,3): prices 20 < 30 < 40, profits 30+40+50 = 120. Maximum is 120.
Example 2 — No Valid Triplet
$ Input: prices = [4,3,2,1], profits = [33,20,19,56]
Output: -1
💡 Note: Prices are in decreasing order, so no triplet (i,j,k) exists where prices[i] < prices[j] < prices[k].
Example 3 — Mixed Order
$ Input: prices = [1,7,3,10,5], profits = [5,10,3,6,4]
Output: 20
💡 Note: Pick indices (0,1,3): prices 1 < 7 < 10, profits 5+10+6 = 21. Pick indices (0,2,3): prices 1 < 3 < 10, profits 5+3+6 = 14. Pick indices (2,4,3) is invalid since 4 > 3. Best valid triplet gives profit 21.

Constraints

  • 3 ≤ prices.length = profits.length ≤ 2000
  • 1 ≤ prices[i] ≤ 5000
  • 1 ≤ profits[i] ≤ 106

Visualization

Tap to expand
Maximum Profitable Triplets With Increasing PricesInput Arrays:10203040prices20304050profitsConstraint: prices[i] < prices[j] < prices[k] where i < j < kValid Triplets:i=0, j=1, k=2: 10<20<30Profit: 20+30+40 = 90i=0, j=1, k=3: 10<20<40Profit: 20+30+50 = 100Maximum: 100Goal: Find triplet that maximizes total profitChallenge: Must satisfy BOTH constraints1. Index order: i < j < k2. Price order: prices[i] < prices[j] < prices[k]
Understanding the Visualization
1
Input
Two arrays: prices and profits of items
2
Constraint
Find triplet (i,j,k) where i < j < k and prices[i] < prices[j] < prices[k]
3
Output
Maximum sum of profits[i] + profits[j] + profits[k]
Key Takeaway
🎯 Key Insight: Fix the middle element and optimize left/right searches for maximum profits
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
28.5K Views
Medium Frequency
~35 min Avg. Time
892 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