Problem Description
Given an array of integers, a mountain triplet is a triple of indices (i, j, k) with i < j < k that satisfies nums[i] < nums[j] and nums[k] < nums[j]. The task is to return the minimum possible sum nums[i] + nums[j] + nums[k] over all mountain triplets. If no mountain triplet exists, return -1.
Key Insights
- For any candidate peak at index j (with 0 < j < n – 1), we need a candidate from the left (i) with nums[i] < nums[j] and a candidate from the right (k) with nums[k] < nums[j].
- To minimize the overall sum, for each j we want the minimal valid number on its left (i) and on its right (k).
- A single linear scan from left to right can maintain a running minimum from all indices before j to quickly determine the minimal candidate on the left.
- A reverse scan from right to left can similarly provide the minimal candidate from indices after j.
- Finally, iterate through each possible j and compute the triplet sum if both candidates exist. The minimum among these sums is the answer.
Space and Time Complexity
Time Complexity: O(n) – we perform two linear passes over the array plus a final iteration. Space Complexity: O(n) – extra arrays are used to store the best candidate from the left and right for each index.
Solution
The solution involves three main steps:
- Create an array (or similar structure) to store the minimum candidate to the left for each index j. Iterate left-to-right, keeping track of the smallest element seen so far. At each index j, if this running minimum is less than nums[j], it is the candidate.
- Create another array to store the minimum candidate to the right for each index j. Iterate right-to-left, similarly maintaining a running minimum for indices after j.
- For every index j (acting as the mountain peak), if valid left and right candidates exist (i.e. they are less than nums[j]), calculate the sum and update the global minimum. If no valid mountain triplet is found, return -1.
The trick is that the overall minimum candidate from the left (or right) will always yield the minimum contribution to the triplet sum for a fixed j, making the approach both simple and efficient.