I keep track of the smallest value seen so far as I iterate through the array. For each element, I check if it’s greater than this minimum value. If it is, I compute the difference and update the maximum difference found so far. If it’s not, I update the minimum value.
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
min_val = nums[0]
max_diff = -1
for num in nums[1:]:
if num > min_val:
max_diff = max(max_diff, num - min_val)
else:
min_val = num
return max_diff
- Time: O(n)
- Space: O(1)