Leetcode 2908. Minimum Sum of Mountain Triplets I Sure! Let’s break this problem down step by step.
Given an array nums
of positive integers, find the minimum sum of elements from three subarrays L
, M
, and N
of length X
, Y
, and Z
respectively, such that L
comes before M
, and M
comes before N
. More formally, the sum of elements in the subarrays should be minimized and the subarrays should be non-overlapping with the order constraint L
< M
< N
.
nums
?X
, Y
, and Z
?L
, M
, and N
)?Assuming the constraints are typical for a leetcode problem, let’s go ahead with the implementation:
X
, Y
, and Z
.N
and for each, find the optimal positions of M
and L
.M
and M
.Here’s how it can be implemented in C++:
#include <vector>
#include <numeric>
#include <climits>
#include <iostream>
int minSumMountainTriplets(std::vector<int>& nums, int X, int Y, int Z) {
int n = nums.size();
if (n < X + Y + Z) return -1; // Not enough elements for the triplets
// Prefix sums
std::vector<int> prefix(n + 1, 0);
for (int i = 0; i < n; ++i) {
prefix[i + 1] = prefix[i] + nums[i];
}
auto subarraySum = [&](int l, int r) {
return prefix[r + 1] - prefix[l];
};
// Define minimum sums for subarrays ending before i
std::vector<int> minLToI(n, INT_MAX);
std::vector<int> minLPlusIToI(n, INT_MAX);
// Fill `minLToI` array for all valid positions of L
for (int i = X - 1; i < n; ++i) {
int sumL = subarraySum(i - X + 1, i);
if (i == X - 1) {
minLToI[i] = sumL;
} else {
minLToI[i] = std::min(minLToI[i - 1], sumL);
}
}
// Fill `minLPlusIToI` array for all valid positions of M (i is end of M)
for (int i = X + Y - 1; i < n; ++i) {
int sumM = subarraySum(i - Y + 1, i);
int minLPlusSumM = minLToI[i - Y] + sumM;
if (i == X + Y - 1) {
minLPlusIToI[i] = minLPlusSumM;
} else {
minLPlusIToI[i] = std::min(minLPlusIToI[i - 1], minLPlusSumM);
}
}
// Find the optimal sum by checking positions of N
int result = INT_MAX;
for (int i = X + Y + Z - 1; i < n; ++i) {
int sumN = subarraySum(i - Z + 1, i);
result = std::min(result, minLPlusIToI[i - Z] + sumN);
}
return result == INT_MAX ? -1 : result;
}
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int X = 2, Y = 3, Z = 2;
std::cout << "Minimum Sum of Mountain Triplets: " << minSumMountainTriplets(nums, X, Y, Z) << std::endl;
return 0;
}
So the overall time complexity is O(n).
This approach ensures we efficiently find the minimum sum of mountain triplets according to the given constraints.
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?