its a very easy question LC but u have to think o(n) solution. There was a hint in the question to note the minimum value as traversing but I took it wrongly like I found the minium value in the nums list and from that index, i compared every number
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
minVal = min(nums)
minIndex = nums.index(minVal)
ans=-1
for i in range(minIndex,len(nums)):
if nums[i]>minVal:
ans=max(ans,nums[i]-minVal)
return ans
but its obiously wrong logic cuz if u have
[2,100,1,10] then we are skippoing the obvious 2,100 answer.
so i thought about the hint deeper. Noting the min number whilte traversing so if current number is less than or equal to minVal, then we update minVal accordingly. Note it has to include the equal cuz if we have [4,4,7] and we dont include that condition, answer is 0, but it should be -1 that we should return
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
# [87,68,91,86,58,63,43,98,6,40]
minVal=int(10e18)
ans=-1
for i in nums:
if i<=minVal:
minVal=i
else:
ans=max(ans,i-minVal)
return ans
n time
1 space