Maximum Profitable Triplets With Increasing Prices I - Problem

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

We need to pick 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, and -1 if it's not possible to pick three items with the given condition.

Input & Output

Example 1 — Basic Case
$ Input: prices = [10,20,30,40], profits = [1,4,3,7]
Output: 14
💡 Note: We can select indices (1,2,3): prices are 20 < 30 < 40 and profits are 4+3+7=14
Example 2 — No Valid Triplet
$ Input: prices = [40,30,20,10], profits = [1,2,3,4]
Output: -1
💡 Note: Prices are in decreasing order, so no valid triplet with increasing prices exists
Example 3 — Multiple Valid Options
$ Input: prices = [1,2,3,4,5], profits = [5,4,3,2,1]
Output: 12
💡 Note: Best triplet is (0,1,2): prices 1 < 2 < 3, profits 5+4+3=12

Constraints

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

Visualization

Tap to expand
Maximum Profitable Triplets with Increasing PricesPrices:10203040Profits:1437Valid triplets (increasing prices):• (0,1,2): 10 < 20 < 30 → profit = 1+4+3 = 8• (0,1,3): 10 < 20 < 40 → profit = 1+4+7 = 12• (0,2,3): 10 < 30 < 40 → profit = 1+3+7 = 11• (1,2,3): 20 < 30 < 40 → profit = 4+3+7 = 14 ✓Maximum Profit: 14Achieved by triplet (1,2,3)
Understanding the Visualization
1
Input Arrays
Two arrays: prices and profits
2
Find Valid Triplets
Triplets (i,j,k) where i < j < k and prices[i] < prices[j] < prices[k]
3
Maximize Profit
Sum profits[i] + profits[j] + profits[k]
Key Takeaway
🎯 Key Insight: For each middle element, find the maximum profit from valid left and right elements to optimize the triplet selection
Asked in
Google 15 Amazon 12 Meta 8
32.0K Views
Medium Frequency
~25 min Avg. Time
850 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