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. Optimal is (1,3,5): nums[1]=4 < nums[3]=7 > nums[5]=2. Sum = 4+7+2 = 13.
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
Minimum Sum of Mountain Triplets II INPUT nums = [8, 6, 1, 5, 3] 8 i=0 6 i=1 1 i=2 5 i=3 3 i=4 Mountain Triplet i < j < k nums[i] < nums[j] > nums[k] i j (peak) k Find triplet with min sum ALGORITHM STEPS 1 Left Min Array leftMin[i] = min of nums[0..i-1] [INF, 8, 6, 1, 1] 2 Right Min Array rightMin[i] = min of nums[i+1..n] [1, 1, 3, 3, INF] 3 Check Each Peak For each j, check if valid peak leftMin[j] < nums[j] > rightMin[j] 4 Calculate Min Sum sum = leftMin[j] + nums[j] + rightMin[j] j=3: peak=5 left=1, right=3 sum = 1 + 5 + 3 = 9 Valid mountain! [OK] FINAL RESULT Minimum Mountain Triplet Found: 1 i=2 5 j=3 3 k=4 1 + 5 + 3 = 9 Output: 9 Key Insight: Two-Pass Optimization: Pre-compute leftMin[] and rightMin[] arrays in O(n) time. For each potential peak j, check if leftMin[j] < nums[j] > rightMin[j] in O(1). Total time complexity: O(n) instead of O(n^3) brute force. Space: O(n) for two arrays. TutorialsPoint - Minimum Sum of Mountain Triplets II | Two-Pass Optimization Approach
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