#2908

Minimum Sum of Mountain Triplets I

Easy
ArrayTwo PointersSliding WindowDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a single pass to find the minimum values for potential mountain triplets. This reduces the number of checks needed and ensures we only look at valid indices.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create two arrays, leftMin and rightMin, to store the minimum values to the left and right of each index.
  2. 2Step 2: Fill leftMin by iterating from left to right, keeping track of the minimum value seen so far.
  3. 3Step 3: Fill rightMin by iterating from right to left, keeping track of the minimum value seen so far.
  4. 4Step 4: Loop through each possible middle index j and check if leftMin[j] < nums[j] and rightMin[j] < nums[j]. If true, calculate the sum and update the minimum sum.
solution.py13 lines
1def minimumMountainTriplet(nums):
2    n = len(nums)
3    leftMin = [float('inf')] * n
4    rightMin = [float('inf')] * n
5    for i in range(1, n):
6        leftMin[i] = min(leftMin[i - 1], nums[i - 1])
7    for i in range(n - 2, -1, -1):
8        rightMin[i] = min(rightMin[i + 1], nums[i + 1])
9    min_sum = float('inf')
10    for j in range(1, n - 1):
11        if leftMin[j] < nums[j] and rightMin[j] < nums[j]:
12            min_sum = min(min_sum, leftMin[j] + nums[j] + rightMin[j])
13    return min_sum if min_sum != float('inf') else -1

Complexity note: The time complexity is O(n) because we traverse the array a constant number of times. The space complexity is O(n) due to the additional arrays used to store the minimum values.

  • 1A mountain triplet requires a peak with valid left and right values.
  • 2Using auxiliary arrays can help optimize the search for valid triplets.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.