Maximum Value of an Ordered Triplet I - Problem
You're given a 0-indexed integer array nums and need to find the maximum value among all possible ordered triplets.
An ordered triplet consists of three indices (i, j, k) where i < j < k. The value of such a triplet is calculated as:
(nums[i] - nums[j]) * nums[k]
Goal: Return the maximum value over all valid triplets. If all triplets have negative values, return 0.
Example: For array [12, 6, 1, 2, 7], the triplet (0, 2, 4) gives us (12 - 1) * 7 = 77, which might be our maximum!
Input & Output
example_1.py โ Basic Positive Result
$
Input:
[12, 6, 1, 2, 7]
โบ
Output:
77
๐ก Note:
The optimal triplet is (i=0, j=2, k=4): (12 - 1) ร 7 = 11 ร 7 = 77. This gives the maximum value among all possible ordered triplets.
example_2.py โ All Negative Values
$
Input:
[1, 10, 3, 4, 19]
โบ
Output:
133
๐ก Note:
The optimal triplet is (i=4, j=1, k=4) - wait, that's invalid since i < j < k must hold. Actually, it's (i=0, j=1, k=4): (1 - 10) ร 19 = -9 ร 19 = -171, which is negative. Let's try (i=1, j=2, k=4): (10 - 3) ร 19 = 7 ร 19 = 133.
example_3.py โ Minimum Length Array
$
Input:
[2, 3, 1]
โบ
Output:
0
๐ก Note:
Only one possible triplet: (i=0, j=1, k=2) gives us (2 - 3) ร 1 = -1 ร 1 = -1, which is negative. Since all triplet values are negative, we return 0.
Visualization
Tap to expand
Understanding the Visualization
1
Track Best Buy Price
As you move through time, remember the highest price you could have bought at (max_i)
2
Track Best Profit Potential
For each selling opportunity, calculate potential profit and remember the best (max_diff)
3
Apply Market Multiplier
When you reach each multiplier day, calculate final return using best profit ร multiplier
Key Takeaway
๐ฏ Key Insight: By maintaining running maximums of the best buy price and best profit potential, we can find the optimal triplet in a single pass through the array, achieving O(n) time complexity.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the array, constant work per element
โ Linear Growth
Space Complexity
O(1)
Only using a few variables to track running maximums
โ Linear Space
Constraints
- 3 โค nums.length โค 105
- 1 โค nums[i] โค 106
- All array elements are positive integers
- Array indices must satisfy i < j < k for valid triplets
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code