You are given a 0-indexed integer array nums.
Return the maximum value over all triplets of indices (i, j, k) such that i < j < k. If all such triplets have a negative value, return 0.
The value of a triplet of indices (i, j, k) is equal to (nums[i] - nums[j]) * nums[k].
Example 1:
Input: nums = [12,6,1,2,7] Output: 77 Explanation: The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) * nums[4] = 77. It can be shown that there are no ordered triplets of indices with a value greater than 77.
Example 2:
Input: nums = [1,10,3,4,19] Output: 133 Explanation: The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) * nums[4] = 133. It can be shown that there are no ordered triplets of indices with a value greater than 133.
Example 3:
Input: nums = [1,2,3] Output: 0 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.
Constraints:
3 <= nums.length <= 1051 <= nums[i] <= 106
Approach 01:
-
C++
-
Python
class Solution {
public:
long long maximumTripletValue(vector<int>& nums) {
long long result = 0;
int num_i = nums[0];
int diff = INT_MIN;
for (int index = 1; index < nums.size() - 1; ++index) {
diff = max(diff, num_i - nums[index]);
num_i = max(num_i, nums[index]);
result = max(result, static_cast<long long>(diff) * nums[index + 1]);
}
return result;
}
};
class Solution:
def maximumTripletValue(self, nums: List[int]) -> int:
diff = float('-inf')
n = len(nums)
num_i = nums[0]
result = 0
for index in range(1,n-1):
diff = max(diff, num_i - nums[index])
num_i = max(num_i, nums[index])
result = max(result, diff*nums[index+1])
return result
Time Complexity:
- Single Pass:
The algorithm iterates through the array once, making updates in \( O(N) \) time.
- Maximum and Difference Computation:
Each element is processed in constant time, leading to an overall time complexity of \( O(N) \).
- Total Time Complexity:
The overall time complexity is \( O(N) \).
Space Complexity:
- Variable Storage:
Only a few integer and long long variables are used, requiring \( O(1) \) space.
- No Extra Data Structures:
Since no additional data structures are used, the total space complexity remains \( O(1) \).