Maximum total profit of three items with strictly increasing prices
Company: Salesforce
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Other
Overview: Given arrays of item prices and profits, choose three indices in order whose prices strictly increase and return the largest total profit, or -1 when no such triplet exists. Tests handling equal prices and finding a faster than quadratic solution for arrays of up to 50,000 items.
Constraints
- 3 <= n <= 5 * 10^4
- price.length == profit.length == n
- 1 <= price[i] <= 10^9
- 1 <= profit[i] <= 10^6
Examples
Input: ([10, 2, 3, 4], [100, 2, 7, 10])
Expected Output: 19
Explanation: Source example 1: the profit-100 item comes first with the highest price, so only (1, 2, 3) is valid, worth 2 + 7 + 10 = 19.
Input: ([4, 3, 2, 1], [33, 20, 19, 87])
Expected Output: -1
Explanation: Source example 2: strictly decreasing prices admit no triplet.
Hints
- Fix the middle item of the triplet. What single number do you need from the items before it, and what from the items after it?
- Two items with the same price can never share a triplet, so every price comparison on both sides has to be strict.
- With n up to 5 * 10^4, trying every triplet or every pair is too slow; aim for a running time well below O(n^2).