Leetcode 2908. Minimum Sum of Mountain Triplets I
You are given an integer array nums
of length n
. Your goal is to find three integers in nums
that satisfy the following conditions:
a < b > c
.Input: nums = [2, 1, 3, 5, 4, 7]
Output: 10
Explanation: The mountain triplet [2, 5, 3] gives the sum as 10.
a < b > c
condition.1 <= nums.length <= 1000
and -10^4 <= nums[i] <= 10^4
.To find the minimum sum of mountain triplets:
b
.b
, find the largest possible a
to the left of b
and the largest possible c
to the right of b
.Integer.MAX_VALUE
).a
(left of peak): Use a nested loop to find the largest element less than the peak before the index of the peak.c
(right of peak): Use a nested loop to find the largest element less than the peak after the index of the peak.a
and c
are found, calculate the sum and update the minimum sum.public class Solution {
public int minimumSumMountainTriplets(int[] nums) {
int n = nums.length;
int minSum = Integer.MAX_VALUE;
boolean found = false;
for (int j = 1; j < n - 1; j++) {
int leftMax = Integer.MIN_VALUE;
int rightMax = Integer.MIN_VALUE;
// Look for the largest element to the left of nums[j]
for (int i = 0; i < j; i++) {
if (nums[i] < nums[j]) {
leftMax = Math.max(leftMax, nums[i]);
}
}
// Look for the largest element to the right of nums[j]
for (int k = j + 1; k < n; k++) {
if (nums[k] < nums[j]) {
rightMax = Math.max(rightMax, nums[k]);
}
}
if (leftMax != Integer.MIN_VALUE && rightMax != Integer.MIN_VALUE) {
found = true;
int currentSum = leftMax + nums[j] + rightMax;
minSum = Math.min(minSum, currentSum);
}
}
return found ? minSum : -1;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {2, 1, 3, 5, 4, 7};
System.out.println(sol.minimumSumMountainTriplets(nums)); // Output: 10
}
}
O(n)
peaks to consider.O(n)
operations for each peak.Thus, the overall time complexity is O(n^2)
.
This solution is efficient given the constraints and ensures that all possible peaks are evaluated to find the minimum sum of mountain triplets.
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?