Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 2908: Minimum Sum of Mountain Triplets I

Array

LeetCode 2908 Solution Explanation

Explanation

To solve this problem, we need to find the minimum sum of a mountain triplet in the given array nums. A mountain triplet is defined as a triplet of indices (i, j, k) where i < j < k and nums[i] < nums[j] and nums[k] < nums[j].

We can iterate through the array and for each element as the middle element of a potential mountain triplet, find the minimum sum by checking all possible left and right elements that satisfy the mountain conditions. If a valid mountain triplet is found, we update the minimum sum.

The time complexity of this approach is O(n^3) where n is the length of the input array nums, as we are checking all possible combinations. The space complexity is O(1) as we are not using any extra space.

LeetCode 2908 Solutions in Java, C++, Python

class Solution {
    public int minMountainTriplets(int[] nums) {
        int n = nums.length;
        int minSum = Integer.MAX_VALUE;

        for (int j = 1; j < n - 1; j++) {
            int leftMin = Integer.MAX_VALUE;
            for (int i = 0; i < j; i++) {
                if (nums[i] < nums[j]) {
                    leftMin = Math.min(leftMin, nums[i]);
                }
            }

            int rightMin = Integer.MAX_VALUE;
            for (int k = j + 1; k < n; k++) {
                if (nums[k] < nums[j]) {
                    rightMin = Math.min(rightMin, nums[k]);
                }
            }

            if (leftMin != Integer.MAX_VALUE && rightMin != Integer.MAX_VALUE) {
                minSum = Math.min(minSum, leftMin + nums[j] + rightMin);
            }
        }

        return minSum == Integer.MAX_VALUE ? -1 : minSum;
    }
}

Interactive Code Editor for LeetCode 2908

Improve Your LeetCode 2908 Solution

Use the editor below to refine the provided solution for LeetCode 2908. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems