Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created April 3, 2025 22:33
Show Gist options
  • Save Ifihan/df3f5e94af92531e7b419dd22f97ff87 to your computer and use it in GitHub Desktop.
Save Ifihan/df3f5e94af92531e7b419dd22f97ff87 to your computer and use it in GitHub Desktop.
Maximum Value of an Ordered Triplet II

Question

Approach

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.

Implementation

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

Complexities

  • Time: O(n)
  • Space: O(n)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment