Leetcode 2873. Maximum Value of an Ordered Triplet I
You are given an integer array nums
. The ordered triplet (a, b, c)
is a valid ordered triplet if the following conditions are satisfied:
0 <= a < b < c < nums.length
nums[a] < nums[b] < nums[c]
Return the maximum value of (nums[a] + nums[b] + nums[c])
among all valid ordered triplets. If no valid triplet exists, return 0
.
nums
?
10^5
.nums
be negative?
0
.(a, b, c)
and check if they form a valid triplet and calculate their sum.O(n^3)
. This is not efficient for large arrays.leftMax[i]
to store the maximum values from the left to i-1
which are less than nums[i]
.rightMax[i]
to store the maximum values from i+1
to the end of the array which are greater than nums[i]
.leftMax
and rightMax
arrays and calculate the possible triplet values efficiently.The time complexity for the optimized approach will be O(n)
for creating the left and right helper arrays plus O(n)
for computing the result, which is O(n)
overall.
Here’s the C++ implementation of the optimized approach:
#include <vector>
#include <algorithm>
#include <limits.h>
int maxValueOrderedTriplet(std::vector<int>& nums) {
int n = nums.size();
if (n < 3) return 0;
std::vector<int> leftMax(n, INT_MIN);
std::vector<int> rightMax(n, INT_MIN);
// Fill leftMax
for (int i = 1; i < n; ++i) {
leftMax[i] = leftMax[i-1];
if (nums[i-1] < nums[i]) {
leftMax[i] = std::max(leftMax[i], nums[i-1]);
}
}
// Fill rightMax
for (int i = n-2; i >= 0; --i) {
rightMax[i] = rightMax[i+1];
if (nums[i+1] > nums[i]) {
rightMax[i] = std::max(rightMax[i], nums[i+1]);
}
}
// Find the maximum triplet sum
int maxSum = 0;
for (int b = 1; b < n-1; ++b) {
if (leftMax[b] != INT_MIN && rightMax[b] != INT_MIN) {
maxSum = std::max(maxSum, leftMax[b] + nums[b] + rightMax[b]);
}
}
return maxSum;
}
// Example usage
// int main() {
// std::vector<int> nums = {1, 2, 3, 4};
// int result = maxValueOrderedTriplet(nums);
// std::cout << "Max value of ordered triplet: " << result << std::endl;
// return 0;
// }
leftMax[i]
: holds the maximum elements to the left of i
which are smaller than nums[i]
.rightMax[i]
: holds the maximum elements to the right of i
which are greater than nums[i]
.leftMax
from left to right by checking for elements smaller than the current element.rightMax
from right to left by checking for elements greater than the current element.This solution ensures that we find the optimal triplet sum in linear time.
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?