Skip to content

Commit d1a7565

Browse files
committed
Sync LeetCode submission Runtime - 260 ms (14.25%), Memory - 30.3 MB (16.13%)
1 parent 3813872 commit d1a7565

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p>
2+
3+
<p>Return <em><strong>the maximum value over all triplets of indices</strong></em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code><em>. </em>If all such triplets have a negative value, return <code>0</code>.</p>
4+
5+
<p>The <strong>value of a triplet of indices</strong> <code>(i, j, k)</code> is equal to <code>(nums[i] - nums[j]) * nums[k]</code>.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
10+
<pre>
11+
<strong>Input:</strong> nums = [12,6,1,2,7]
12+
<strong>Output:</strong> 77
13+
<strong>Explanation:</strong> The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) * nums[4] = 77.
14+
It can be shown that there are no ordered triplets of indices with a value greater than 77.
15+
</pre>
16+
17+
<p><strong class="example">Example 2:</strong></p>
18+
19+
<pre>
20+
<strong>Input:</strong> nums = [1,10,3,4,19]
21+
<strong>Output:</strong> 133
22+
<strong>Explanation:</strong> The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) * nums[4] = 133.
23+
It can be shown that there are no ordered triplets of indices with a value greater than 133.
24+
</pre>
25+
26+
<p><strong class="example">Example 3:</strong></p>
27+
28+
<pre>
29+
<strong>Input:</strong> nums = [1,2,3]
30+
<strong>Output:</strong> 0
31+
<strong>Explanation:</strong> 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.
32+
</pre>
33+
34+
<p>&nbsp;</p>
35+
<p><strong>Constraints:</strong></p>
36+
37+
<ul>
38+
<li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
39+
<li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li>
40+
</ul>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Approach 1: Greedy + Prefix Suffix Array
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
class Solution:
7+
def maximumTripletValue(self, nums: List[int]) -> int:
8+
n = len(nums)
9+
left_max = [0] * n
10+
right_max = [0] * n
11+
12+
for i in range(1, n):
13+
left_max[i] = max(left_max[i - 1], nums[i - 1])
14+
right_max[n - i - 1] = max(right_max[n - i], nums[n - i])
15+
16+
res = 0
17+
for j in range(1, n - 1):
18+
res = max(res, (left_max[j] - nums[j]) * right_max[j])
19+
20+
return res
21+

0 commit comments

Comments
 (0)