Problem Description
Given a 0-indexed integer array nums, find the maximum value of any ordered triplet (i, j, k) with i < j < k where the value is defined by (nums[i] - nums[j]) * nums[k]. If every triplet yields a negative value, return 0.
Key Insights
- The triplet value (nums[i] - nums[j]) * nums[k] is only positive when nums[i] > nums[j] and nums[k] is large.
- Using three nested loops (i, j, k) is acceptable for n ≤ 100, though optimization is possible.
- Alternatively, for each middle index j, one can track the maximum element before j (to maximize nums[i] - nums[j]) and the maximum element after j (to maximize nums[k]).
- By precomputing a prefix maximum and suffix maximum, the problem reduces to iterating over j and computing: candidate = (prefix_max[j-1] - nums[j]) * suffix_max[j+1] and taking the maximum candidate.
Space and Time Complexity
Time Complexity: O(n) when using prefix and suffix arrays (with two passes plus one pass for evaluation).
Space Complexity: O(n) for maintaining the prefix and suffix arrays.
Solution
We can optimize the solution by computing two auxiliary arrays: one for the prefix maximum (max value before the current index) and one for the suffix maximum (max value after the current index).
- Create a prefix_max array so that for each index j, prefix_max[j] holds the maximum number from index 0 to j.
- Create a suffix_max array so that for each index j, suffix_max[j] holds the maximum number from j to the end of the array.
- Then, iterate over the possible middle elements (j from 1 to n-2) and compute:
candidate = (prefix_max[j-1] - nums[j]) * suffix_max[j+1] - Track the maximum candidate over all valid j. Return the maximum candidate if it is more than 0; otherwise, return 0.