Leetcode 2873. Maximum Value of an Ordered Triplet I
Given an integer array nums
, you need to find the maximum value of an ordered triplet (nums[i], nums[j], nums[k])
such that 0 <= i < j < k < n
and nums[i] <= nums[j] <= nums[k]
. Your task is to return the maximum value of such a triplet from the array.
nums[i] <= nums[j] <= nums[k]
is satisfied?
i
, j
, and k
satisfy 0 <= i < j < k < n
.nums[i]
, nums[j]
, and nums[k]
.public class MaxValueOrderedTriplet {
public int maximumTripletValue(int[] nums) {
int n = nums.length;
// Early exit if the array length is less than 3, no triplet can be formed.
if (n < 3) {
throw new IllegalArgumentException("Array length must be at least 3");
}
// Variables to keep track of potential values of the triplet
int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE;
for (int i = 0; i < n - 2; i++) {
for (int j = i + 1; j < n - 1; j++) {
for (int k = j + 1; k < n; k++) {
if (nums[i] <= nums[j] && nums[j] <= nums[k]) {
int tripletValue = nums[i] + nums[j] + nums[k];
if (tripletValue > max3) {
max3 = tripletValue;
}
}
}
}
}
return max3;
}
public static void main(String[] args) {
MaxValueOrderedTriplet solution = new MaxValueOrderedTriplet();
int[] nums = {1, 2, 3, 4, 5};
System.out.println(solution.maximumTripletValue(nums)); // Expected Output: 9
}
}
The time complexity of the above solution is O(n^3) due to the triple nested loops over the array.
However, this approach is not efficient for larger arrays. An optimal solution would involve improved traversal and potentially using more advanced data structures to maintain the current state efficiently in O(n log n) or O(n).
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?