Skip to content

Commit c505e31

Browse files
committed
@Solution: Maximum Value of an Ordered Triplet II
1 parent f2dc0a2 commit c505e31

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Maximum Value of an Ordered Triplet II
2+
3+
You are given a 0-indexed integer array nums.
4+
5+
Return the maximum value over all triplets of indices (i, j, k) such that i < j < k. If all such triplets have a
6+
negative value, return 0.
7+
8+
The value of a triplet of indices (i, j, k) is equal to (nums[i] - nums[j]) * nums[k].
9+
10+
Example 1:
11+
12+
```
13+
Input: nums = [12,6,1,2,7]
14+
Output: 77
15+
Explanation: The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) * nums[4] = 77.
16+
It can be shown that there are no ordered triplets of indices with a value greater than 77.
17+
```
18+
19+
Example 2:
20+
21+
```
22+
Input: nums = [1,10,3,4,19]
23+
Output: 133
24+
Explanation: The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) * nums[4] = 133.
25+
It can be shown that there are no ordered triplets of indices with a value greater than 133.
26+
```
27+
28+
Example 3:
29+
30+
```
31+
Input: nums = [1,2,3]
32+
Output: 0
33+
Explanation: The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) * nums[2] = -3. Hence, the answer would be 0.
34+
```
35+
36+
**Constraints:**
37+
38+
- 3 <= nums.length <= 10^5
39+
- 1 <= nums[i] <= 10^6
40+
41+
[Link](https://leetcode.com/problems/maximum-value-of-an-ordered-triplet-ii/description)
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def maximumTripletValue(self, nums: List[int]) -> int:
6+
n = len(nums)
7+
result, imax, tmp = 0, 0, 0
8+
for i in range(n):
9+
result = max(result, tmp * nums[i])
10+
tmp = max(tmp, imax - nums[i])
11+
imax = max(imax, nums[i])
12+
return result
13+
14+
15+
s = Solution()
16+
print(s.maximumTripletValue([12, 6, 1, 2, 7]))
17+
print(s.maximumTripletValue([1, 10, 3, 4, 19]))
18+
print(s.maximumTripletValue([1, 2, 3]))
19+
print(s.maximumTripletValue([1, 3]))

0 commit comments

Comments
 (0)