Largest Later-Minus-Earlier Difference
Problem statement
You are given an integer array nums. Pick two indices i < j and compute nums[j] - nums[i]: a later number minus an earlier one.
Return the largest value of nums[j] - nums[i] over all such pairs. The answer can be 0 or negative, for example when the numbers never go up.
Function
maxDifference(nums: int[]) → intExamples
Example 1
nums = [4,9,1,7,3]return = 6Taking 4 then 9 gives 9 - 4 = 5. Taking 1 (index 2) then 7 (index 3) gives 7 - 1 = 6, which is the largest. The 9 and the 1 do not give 8, because the 1 comes after the 9. The answer is 6.
Example 2
nums = [8,5,3,2]return = -1The numbers only go down, so every later-minus-earlier difference is negative. The closest pair is 3 then 2, which gives 2 - 3 = -1. The answer is -1.
Example 3
nums = [6,6]return = 0The only pair gives 6 - 6 = 0. The answer is 0.
Constraints
2 <= nums.length <= 5 * 10^4-10^6 <= nums[i] <= 10^6