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 Prices INPUT prices[] 10 20 30 40 i=0 i=1 i=2 i=3 profits[] 1 4 3 7 Condition: prices[i] < prices[j] < prices[k] where i < j < k ALGORITHM STEPS 1 Fix Middle Element j Iterate j from 1 to n-2 2 Find Best Left (i < j) Max profit where price[i]<price[j] 3 Find Best Right (k > j) Max profit where price[k]>price[j] 4 Calculate Total Profit Sum: left + middle + right Example: j=1 (price=20, profit=4) Left i=0: price=10 < 20 [OK] best_left = 1 Right k=3: price=40 > 20 [OK] best_right = 7 Total = 1 + 4 + 7 = 12 FINAL RESULT Valid Triplets Found: j=1: (10,20,30) or (10,20,40) Best: 1+4+7 = 12 j=2: (10,30,40) or (20,30,40) Best: 4+3+7 = 14 Optimal Selection: i=1 20,4 j=2 30,3 k=3 40,7 Maximum Profit 14 4 + 3 + 7 Key Insight: Middle Element Approach By fixing the middle element j, we decompose the problem into finding the best left element (i < j with prices[i] < prices[j]) and best right element (k > j with prices[k] > prices[j]). This allows efficient computation using prefix/suffix arrays or segment trees for optimal O(n log n) time complexity. TutorialsPoint - Maximum Profitable Triplets With Increasing Prices I | Middle Element Approach
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