LeetCode 2909: Minimum Sum of Mountain Triplets II Solution
Master LeetCode problem 2909 (Minimum Sum of Mountain Triplets II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2909. Minimum Sum of Mountain Triplets II
Problem Explanation
Explanation
To find the minimum sum of a mountain triplet in the given array, we need to iterate through the array and for each element nums[j], we need to find the minimum elements nums[i] and nums[k] such that i < j and j < k and nums[i] < nums[j] and nums[k] < nums[j]. We can maintain two arrays, left and right, to store the minimum elements on the left and right side of each element respectively. Then we can iterate through the array and for each element nums[j], we can calculate the sum of the triplet and keep track of the minimum sum.
- Initialize two arrays,
leftandright, to store the minimum element on the left and right side of each element. - Iterate through the array to fill the
leftarray with minimum values on the left side. - Iterate through the array in reverse to fill the
rightarray with minimum values on the right side. - Iterate through the array to find the minimum sum of mountain triplets.
Time complexity: O(n) Space complexity: O(n)
Solution Code
class Solution {
public int minMountainTriples(int[] nums) {
int n = nums.length;
int[] left = new int[n];
int[] right = new int[n];
left[0] = Integer.MAX_VALUE;
for (int i = 1; i < n; i++) {
left[i] = Math.min(left[i - 1], nums[i - 1]);
}
right[n - 1] = Integer.MAX_VALUE;
for (int i = n - 2; i >= 0; i--) {
right[i] = Math.min(right[i + 1], nums[i + 1]);
}
int minSum = Integer.MAX_VALUE;
for (int j = 1; j < n - 1; j++) {
if (nums[j] > left[j] && nums[j] > right[j]) {
minSum = Math.min(minSum, nums[j] + left[j] + right[j]);
}
}
return minSum == Integer.MAX_VALUE ? -1 : minSum;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2909 (Minimum Sum of Mountain Triplets II)?
This page provides optimized solutions for LeetCode problem 2909 (Minimum Sum of Mountain Triplets II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2909 (Minimum Sum of Mountain Triplets II)?
The time complexity for LeetCode 2909 (Minimum Sum of Mountain Triplets II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2909 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2909 in Java, C++, or Python.