714123. Maximum Triplet product
Medium
Maximum Triplet Product
Summary
Given an array of integers, find the maximum product that can be obtained by selecting three elements from the array. The problem is related to arrays and mathematical concepts.
Detailed Explanation
The problem can be solved by finding all possible triplets in the array and then calculating their products. We can use a brute force approach or optimize it using sorting.
Here's a step-by-step breakdown of the solution:
- Sort the array in descending order.
- Initialize the maximum product as 0.
- Iterate through the array, considering each element as the first element of a triplet.
- For each element, consider its two neighbors (to the left and right) to form a triplet.
- Calculate the product of the three elements and update the maximum product if necessary.
- Repeat steps 3-5 until all elements have been considered.
Time complexity: O(n log n) due to sorting Space complexity: O(1)
Here's an ASCII art diagram representing the array:
[ a, b, c, d, e ]
Optimized Solutions
Java
public class MaximumTripletProduct {
public static int findMaximumTriplet(int[] arr) {
Arrays.sort(arr);
int maxProduct = 0;
for (int i = 0; i < arr.length - 2; i++) {
if (arr[i] < 0 && arr[i + 1] < 0) {
continue; // skip negative numbers
}
int product = arr[i] * arr[i + 1] * arr[i + 2];
maxProduct = Math.max(maxProduct, product);
}
return maxProduct;
}
}