To solve this, I tracked the maximum value seen before index j to simulate the best nums[i] where i < j. Then, for each possible k > j, I computed the value of the expression and updated the result if it was higher. I returned the maximum such value, or 0 if all were negative.
class Solution:
def maximumTripletValue(self, nums: List[int]) -> int:
max_i = nums[0]
max_diff = float('-inf')
max_value = 0
for j in range(1, len(nums) - 1):
max_diff = max(max_diff, max_i - nums[j])
max_value = max(max_value, max_diff * nums[j + 1])
max_i = max(max_i, nums[j])
return max_value
- Time: O(n)
- Space: O(n)
