Problem Description
Given a 0-indexed array nums of integers, find three indices (i, j, k) such that i < j < k and they form a mountain pattern (nums[i] < nums[j] and nums[k] < nums[j]). Return the minimum possible sum (nums[i] + nums[j] + nums[k]) of such a triplet. If no valid mountain triplet exists, return -1.
Key Insights
- The triplet must satisfy i < j < k with nums[i] < nums[j] and nums[k] < nums[j].
- Since the array length is small (up to 50), a brute force triple nested loop checking all possible combinations is feasible.
- Alternatively, one may precompute the minimum valid candidate on the left and right for each potential center index j to optimize the solution.
- Always check that for a given j, there is at least one valid i and k, otherwise skip.
Space and Time Complexity
Time Complexity: O(n^3) in the brute-force approach (n <= 50, so it is acceptable) Space Complexity: O(1) extra space aside from the input variable
Solution
We use a brute-force approach by iterating over every possible triplet (i, j, k) such that i < j < k. For every candidate triplet, we check if nums[i] < nums[j] and nums[k] < nums[j]. If the condition holds, we update the minimum sum. Since the constraint allows for n up to 50, this approach is efficient enough. The trick here is to ensure that we only consider valid mountain triplets and handle cases where no valid triplet exists by returning -1.