LeetCode 2909: Minimum Sum of Mountain Triplets II

Array

LeetCode 2909 Solution 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.

  1. Initialize two arrays, left and right, to store the minimum element on the left and right side of each element.
  2. Iterate through the array to fill the left array with minimum values on the left side.
  3. Iterate through the array in reverse to fill the right array with minimum values on the right side.
  4. Iterate through the array to find the minimum sum of mountain triplets.

Time complexity: O(n) Space complexity: O(n)

LeetCode 2909 Solutions in Java, C++, Python

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;
    }
}

Interactive Code Editor for LeetCode 2909

Improve Your LeetCode 2909 Solution

Use the editor below to refine the provided solution for LeetCode 2909. 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