You are given a 0-indexed integer array nums
of length n
. A triplet (i, j, k)
is considered a mountain triplet if the following conditions hold:
0 <= i < j < k < n
nums[i] < nums[j] > nums[k]
Your goal is to find the minimum sum of a mountain triplet or return -1 if no mountain triplet exists.
Input: nums = [1, 3, 1, 2, 4, 1]
Output: 5
Explanation: The triplet (0, 1, 2) is a mountain triplet with the sum 1 + 3 + 1 = 5.
n
(length of nums
)?nums
? Are they positive, negative, or both?n
is less than 3 and return -1?Once these clarifications are made, we can proceed with the solution.
left_min
and right_min
, where:
left_min[j]
will store the minimum value to the left of j
for all valid i
.right_min[j]
will store the minimum value to the right of j
for all valid k
.nums
array to fill up the left_min
and right_min
arrays.j
as the middle element of the triplet.j
, look at the potential values from left_min
and right_min
to calculate the triplet sum.left_min
and right_min
arrays.def minimum_sum_mountain_triplet(nums):
n = len(nums)
if n < 3:
return -1
left_min = [None] * n
right_min = [None] * n
left_min[0] = float('inf')
for j in range(1, n):
left_min[j] = min(left_min[j - 1], nums[j - 1])
right_min[n - 1] = float('inf')
for j in range(n - 2, -1, -1):
right_min[j] = min(right_min[j + 1], nums[j + 1])
min_sum = float('inf')
found = False
for j in range(1, n - 1):
if left_min[j] < nums[j] and nums[j] > right_min[j]:
found = True
min_sum = min(min_sum, left_min[j] + nums[j] + right_min[j])
return min_sum if found else -1
# Example usage
nums = [1, 3, 1, 2, 4, 1]
print(minimum_sum_mountain_triplet(nums)) # Output: 5
n
.nums
elements.After the initial confirmation and understanding, the approach is optimized for both run-time and space complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?