#2909

Minimum Sum of Mountain Triplets II

Medium
ArrayPrefix/Suffix ArraysTwo Pointers
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)

By preprocessing the array to find the smallest values to the left and right of each index, we can efficiently find valid mountain triplets without checking all combinations.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a prefix minimum array where prefix_min[i] is the minimum value from nums[0] to nums[i].
  2. 2Step 2: Create a suffix minimum array where suffix_min[i] is the minimum value from nums[i] to nums[n-1].
  3. 3Step 3: Iterate through each index j from 1 to n-2 and check if nums[j] can form a mountain triplet using prefix_min and suffix_min.
  4. 4Step 4: If valid i and k are found, calculate the sum and update the minimum sum.
  5. 5Step 5: Return the minimum sum found, or -1 if no triplet exists.
solution.py15 lines
1def minimumMountainTriplet(nums):
2    n = len(nums)
3    prefix_min = [float('inf')] * n
4    suffix_min = [float('inf')] * n
5    prefix_min[0] = nums[0]
6    for i in range(1, n):
7        prefix_min[i] = min(prefix_min[i - 1], nums[i])
8    suffix_min[n - 1] = nums[n - 1]
9    for i in range(n - 2, -1, -1):
10        suffix_min[i] = min(suffix_min[i + 1], nums[i])
11    min_sum = float('inf')
12    for j in range(1, n - 1):
13        if nums[j] > prefix_min[j - 1] and nums[j] > suffix_min[j + 1]:
14            min_sum = min(min_sum, prefix_min[j - 1] + nums[j] + suffix_min[j + 1])
15    return min_sum if min_sum != float('inf') else -1

Complexity note: This complexity is linear because we only pass through the array a constant number of times to build the prefix and suffix arrays, and then once more to find the minimum sum.

  • 1Preprocessing helps reduce the number of comparisons needed to find valid triplets.
  • 2Understanding the structure of the problem allows for more efficient algorithms.

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