Created
April 3, 2025 17:57
-
-
Save tatsuyax25/3c6b02f023be41d7376c1128f05c9ed9 to your computer and use it in GitHub Desktop.
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[]} nums | |
* @return {number} | |
*/ | |
var maximumTripletValue = function(nums) { | |
const n = nums.length; | |
if (n < 3) return 0; // Edge case: no valid triplet possible | |
// Arrays to store the maximum values | |
const leftMax = new Array(n).fill(Number.MIN_SAFE_INTEGER); | |
const rightMax = new Array(n).fill(Number.MIN_SAFE_INTEGER); | |
// Precompute leftMax | |
for (let i = 1; i < n; i++) { | |
leftMax[i] = Math.max(leftMax[i - 1], nums[i - 1]); | |
} | |
// Precompute rightMax | |
for (let i = n - 2; i >= 0; i--) { | |
rightMax[i] = Math.max(rightMax[i + 1], nums[i + 1]); | |
} | |
let maxValue = 0; // Initialize maximum value | |
// Iterate through each valid `j` and calculate the value | |
for (let j = 1; j < n - 1; j++) { | |
if (leftMax[j] !== Number.MIN_SAFE_INTEGER && rightMax[j] !== Number.MIN_SAFE_INTEGER) { | |
const tripletValue = (leftMax[j] - nums[j]) * rightMax[j]; | |
maxValue = Math.max(maxValue, tripletValue); | |
} | |
} | |
return maxValue; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment