#2873
Maximum Value of an Ordered Triplet I
EasyArrayArrayDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n³) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
Instead of checking all triplets, we can optimize our approach by precomputing the maximum values for nums[k] and using them to calculate the maximum triplet value efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Initialize max_value to 0 and create an array max_k to store maximum values of nums[k] for each index.
- 2Step 2: Fill max_k such that max_k[k] contains the maximum value of nums from index k to the end.
- 3Step 3: Iterate through the array with two loops to find i and j, and use max_k to compute the triplet value efficiently.
solution.py12 lines
1# Full working Python code
2nums = [12, 6, 1, 2, 7]
3max_k = [0] * len(nums)
4max_k[-1] = nums[-1]
5for i in range(len(nums) - 2, -1, -1):
6 max_k[i] = max(max_k[i + 1], nums[i])
7max_value = 0
8for i in range(len(nums) - 2):
9 for j in range(i + 1, len(nums) - 1):
10 value = (nums[i] - nums[j]) * max_k[j + 1]
11 max_value = max(max_value, value)
12print(max_value)ℹ
Complexity note: The time complexity is O(n²) due to the two nested loops, while the space complexity is O(n) for the max_k array.
- 1The value of the triplet is influenced heavily by the choice of k, as it multiplies the difference between nums[i] and nums[j].
- 2Maximizing nums[k] while minimizing nums[j] relative to nums[i] is key to maximizing the triplet value.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.