2874. Maximum Value of an Ordered Triplet II #41
-
2874. Maximum Value of an Ordered Triplet II📌 Problem StatementYou are given a The value of the triplet ✅ Approach & SolutionSince the constraints are large ( Algorithm
📌 Code Implementationfrom typing import List
class Solution:
def maximumTripletValue(self, nums: List[int]) -> int:
ans = mx = mx_diff = 0
for x in nums:
ans = max(ans, mx_diff * x)
mx_diff = max(mx_diff, mx - x)
mx = max(mx, x)
return ans 🔥 Complexity Analysis
🛠 Example WalkthroughExample 1🔹 Example 2🔹 Example 3🔹 🚀 Alternative Approaches1️⃣ Brute Force (O(n³))
2️⃣ Using Prefix Arrays (O(n²))
📌 Why is our approach optimal? ❓ Discussion💬 Q: Can this handle large inputs efficiently? 💬 Q: What if all values in 💬 Q: Can we solve this using DP? 💬 Q: What are some edge cases we should test? 💬 Q: Could this be optimized further? 🔥 PRs & Issues Welcome!👥 Feel free to suggest optimizations or discuss edge cases! 🚀 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
from typing import List
class Solution:
def maximumTripletValue(self, nums: List[int]) -> int:
n = len(nums)
if n < 3:
return 0
# Prefix max array
prefix_max = [0] * n
prefix_max[0] = nums[0]
for i in range(1, n):
prefix_max[i] = max(prefix_max[i - 1], nums[i])
# Suffix max array
suffix_max = [0] * n
suffix_max[-1] = nums[-1]
for i in range(n - 2, -1, -1):
suffix_max[i] = max(suffix_max[i + 1], nums[i])
# Compute the maximum triplet value
ans = 0
for j in range(1, n - 1):
max_i = prefix_max[j - 1]
max_k = suffix_max[j + 1]
ans = max(ans, (max_i - nums[j]) * max_k)
return ans |
Beta Was this translation helpful? Give feedback.
ok