- Given a 0-indexed integer array
nums
of sizen
, find the maximum difference betweennums[i]
andnums[j]
(i.e.,nums[j] - nums[i]
), such that0 <= i < j < n
andnums[i] < nums[j]
. - Return the maximum difference. If no such
i
andj
exists, return-1
. - https://leetcode.com/problems/maximum-difference-between-increasing-elements/description/
def maximumDifference(self, nums: List[int]) -> int:
minVal = float('inf')
diff = -1
for n in nums:
if n < minVal:
minVal = min(n,minVal)
else:
currDiff = n - minVal
if currDiff > 0:
diff = max(diff, currDiff)
return diff
trick
- track the smallest number, and if the number is STRICTLY greater than the smallest num then we get the difference