Ctrl K

Rising-Price Trio

Hard
A shelf holds n items in a row. Item i has cost costs[i] and gain gains[i]. Pick three items at positions i < j < k whose costs strictly rise from left to right: costs[i] < costs[j] < costs[k]. The gain of such a trio is gains[i] + gains[j] + gains[k]. Return the largest gain of a valid trio, or -1 if no trio can be picked.
Example 1
costs=[7, 3, 5, 4, 9], gains=[50, 6, 8, 20, 10] → 36

The most profitable item (cost 7) is useless: only 9 is dearer after it, with nothing to make a third. The best trio is costs 3 < 4 < 9: 6 + 20 + 10 = 36.

Example 2
costs=[2, 2, 2, 3], gains=[1, 1, 1, 1] → -1

Costs must strictly rise, and the three equal 2s cannot do that — no trio exists, the answer is -1.

Example 3
costs=[1, 2, 3], gains=[4, 5, 6] → 15

The only trio is all three items: 4 + 5 + 6 = 15.

Constraints
  • 3 ≤ costs.length = gains.length ≤ 50,000
  • 1 ≤ costs[i] ≤ 5000
  • 1 ≤ gains[i] ≤ 10⁶
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsCity Block Outline HardSmaller Values to the Right HardWindow Sums Within a Band HardPairs With a Steep Drop HardA Dark Gap Between Street Lamps Hard
loading Python…
Input
costs=[7, 3, 5, 4, 9], gains=[50, 6, 8, 20, 10]
Expected
36

Run checks the first 3 tests in your browser. Submit checks all 127 tests on the server, hidden ones included.