Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created June 16, 2025 20:38
Show Gist options
  • Save tatsuyax25/1ecd9aec53acb40b492f1dbea3f47862 to your computer and use it in GitHub Desktop.
Save tatsuyax25/1ecd9aec53acb40b492f1dbea3f47862 to your computer and use it in GitHub Desktop.
Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j]. Return the maximum difference. If no such i and j exists, return -1.
/**
* @param {number[]} nums
* @return {number}
*/
var maximumDifference = function(nums) {
// Edge case: If the array has fewer than 2 elements, there's no valid pair.
if (nums.length < 2) return -1;
let minSoFar = nums[0]; // Track the smallest element seen so far
let maxDiff = -1; // Initialize max difference to -1 (default if no valid pair is found)
// Iterate through the array from index 1 onward
for (let j = 1; j < nums.length; j++) {
// If nums[j] is greater than the smallest value encountered, update maxDiff
if (nums[j] > minSoFar) {
maxDiff = Math.max(maxDiff, nums[j] - minSoFar);
}
// Update minSoFar to track the smallest element
minSoFar = Math.min(minSoFar, nums[j]);
}
return maxDiff; // Return the maximum difference found
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment