Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created April 2, 2025 17:32
Show Gist options
  • Save tatsuyax25/56ff1536340a0681a10019500428583e to your computer and use it in GitHub Desktop.
Save tatsuyax25/56ff1536340a0681a10019500428583e 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
/**
* @param {number[]} nums
* @return {number}
*/
var maximumTripletValue = function(nums) {
// Initialize the maximum value to 0 (default if all values are negative)
let maxValue = 0;
// Outer loop: Fix the first index i
for (let i = 0; i < nums.length - 2; i++) {
// Middle loop: Fix the second index j (must be greater than i)
for (let j = i + 1; j < nums.length - 1; j++) {
// Inner loop: Fix the third index k (must be greater than j)
for (let k = j + 1; k < nums.length; k++) {
// Calculate the value for the triplet (i, j, k)
let value = (nums[i] - nums[j]) * nums[k];
// Update the maximum value if the current value is greater
maxValue = Math.max(maxValue, value);
}
}
}
// Return the maximum value; if all are negative, the result is still 0
return maxValue;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment