Problem Description
Given a 0-indexed integer array nums, we need to find the maximum value among all triplets (i, j, k) such that i < j < k, where the value of a triplet is defined as (nums[i] - nums[j]) * nums[k]. If every possible triplet yields a negative value, return 0.
Key Insights
- The order i < j < k forces us to consider elements to the left and right of a chosen middle element j.
- For any fixed middle element nums[j], the best candidate for nums[i] is the maximum element to its left (to maximize nums[i] - nums[j]).
- Similarly, the best candidate for nums[k] is the maximum element to its right.
- Precomputing the maximum value on the right side for each element (using a suffix maximum) can help efficiently evaluate each potential middle index.
- The overall maximum is the best value from (leftMax - nums[j]) * rightMax for each valid j; if negative, the answer should be 0.
Space and Time Complexity
Time Complexity: O(n) – We traverse the array to compute the suffix maximum and then another pass to compute the best triplet value. Space Complexity: O(n) – Additional space is used for the suffix maximum array, though it can sometimes be optimized to O(1) with a reverse traversal.
Solution
We approach the problem by iterating through the array while keeping track of the maximum value seen so far from the left (for potential nums[i]). Meanwhile, we precompute a suffix array rightMax where for each index j, rightMax[j] contains the maximum value found in nums from index j+1 to the end (for potential nums[k]). For each index j (acting as the middle element), we compute the candidate value as (leftMax - nums[j]) * rightMax[j] and update the maximum result. Finally, we return 0 if the computed maximum is negative.