Minimum Sum of Mountain Triplets II - Problem

You are given a 0-indexed array nums of integers.

A triplet of indices (i, j, k) is a mountain if:

  • i < j < k
  • nums[i] < nums[j] and nums[k] < nums[j]

Return the minimum possible sum of a mountain triplet of nums. If no such triplet exists, return -1.

Input & Output

Example 1 — Basic Mountain
$ Input: nums = [8,6,1,5,3]
Output: 9
💡 Note: Triplet (2,3,4) forms a mountain: nums[2]=1 < nums[3]=5 > nums[4]=3. Sum = 1+5+3 = 9.
Example 2 — Multiple Mountains
$ Input: nums = [5,4,8,7,10,2]
Output: 13
💡 Note: Multiple valid mountains exist. Triplet (1,2,3) gives nums[1]=4 < nums[2]=8 > nums[3]=7. Sum = 4+8+7 = 19. But (1,4,5) gives 4 < 10 > 2 with sum = 16. Optimal is (0,4,5): 5 < 10 > 2 = 17. Actually, (1,2,5): 4 < 8 > 2 = 14. Best is (0,2,5): 5 < 8 > 2 = 15. Wait, let me recalculate: (1,4,5): 4 < 10 > 2 = 16, (0,4,5): 5 < 10 > 2 = 17, (1,2,5): 4 < 8 > 2 = 14, (0,2,5): 5 < 8 > 2 = 15, (1,2,3): 4 < 8 > 7 = 19. Minimum is 14.
Example 3 — No Mountain
$ Input: nums = [6,5,4,3,4,5]
Output: -1
💡 Note: No valid mountain triplet exists. Elements either increase or decrease monotonically in segments, preventing mountain formation.

Constraints

  • 3 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 108

Visualization

Tap to expand
Mountain Triplets: Find (i,j,k) where nums[i] < nums[j] > nums[k]Input: [8, 6, 1, 5, 3]86153i=0i=1i=2j=3k=4Valid Mountain: (2,3,4)nums[2]=1 < nums[3]=5 > nums[4]=3 ✓Sum = 1 + 5 + 3 = 9Output: 9 (minimum mountain sum)
Understanding the Visualization
1
Input Array
Given array with mountain pattern potential
2
Find Mountains
Identify triplets forming mountain shape
3
Minimum Sum
Return smallest sum among valid mountains
Key Takeaway
🎯 Key Insight: Use precomputed left/right minimums to efficiently find valid mountain triplets
Asked in
Google 15 Facebook 12 Amazon 8
23.4K Views
Medium Frequency
~25 min Avg. Time
847 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