Maximum Increasing Triplet Value Problem
#3073
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3073.
Given an array nums, return the maximum value of a triplet (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k].
The value of a triplet (i, j, k) is nums[i] - nums[j] + nums[k].
Example 1:
Input: nums = [5,6,9]
Output: 8
Explanation: We only have one choice for an increasing triplet and that is choosing all three elements. The value of this triplet would be 5 - 6 + 9 = 8.
Example 2:
Input: nums = [1,5,3,6]
Output: 4
Explanation: There are only two increasing triplets:
(0, 1, 3): The value of this triplet is nums[0] - nums[1] + nums[3] = 1 - 5 + 6 = 2.
(0, 2, 3): The value of this triplet is nums[0] - nums[2] + nums[3] = 1 - 3 + 6 = 4.
Thus the answer would be 4.
Constraints:
3 <= nums.length <= 10^51 <= nums[i] <= 10^9- The input is generated such that at least one triplet meets the given condition.
Solution
Approach: Suffix Maximum + Ordered Set
Fix the middle element nums[j]. The best nums[k] is the largest value to the right of j, which a suffix maximum array right gives. The best nums[i] is the largest value to the left of j that is still smaller than nums[j]. In C++ and Java an ordered set returns it in O(log n); in the other languages we get the same result with a binary indexed tree over value ranks that stores prefix maximums.
Complexity: O(n log n) time and O(n) extra space, where n is the length of nums.
from bisect import bisect_left
class BinaryIndexedTree:
__slots__ = "n", "c"
def __init__(self, n: int):
self.n = n
self.c = [0] * (n + 1)
def update(self, x: int, v: int) -> None:
while x <= self.n:
self.c[x] = max(self.c[x], v)
x += x & -x
def query(self, x: int) -> int:
s = 0
while x:
s = max(s, self.c[x])
x -= x & -x
return s
class Solution:
def maximumTripletValue(self, nums: List[int]) -> int:
n = len(nums)
right = [nums[-1]] * n
for i in range(n - 2, -1, -1):
right[i] = max(nums[i], right[i + 1])
st = sorted(set(nums))
tree = BinaryIndexedTree(len(st))
tree.update(bisect_left(st, nums[0]) + 1, nums[0])
ans = 0
for j in range(1, n - 1):
i = bisect_left(st, nums[j])
if right[j + 1] > nums[j]:
left = tree.query(i)
if left > 0:
ans = max(ans, left - nums[j] + right[j + 1])
tree.update(i + 1, nums[j])
return ans