2441 Largest Positive Integer That Exists With Its Negative
Approach 1: Sorting + two pointers
fromheapqimportheapify,heappush,heappopclassSolution:deffindMaxK(self,nums:List[int])->int:""" objective: - find the largest positive negative pair (1,-1) observation: - it doesn't contain zero solution 1: - maintain a max heap and a min heap, keep popping the the last value until meet be the same, O(n) in time & space. solution 2: - sort it, then two pointer O(nlogn) O(1) """nums.sort()l,r=0,len(nums)-1found=Falseres=Nonewhilel<r:# not possible caseifnums[l]>0ornums[r]<0:break# base caseifnums[l]==-nums[r]:found=Trueres=nums[r]break# going the absolutely smaller oneifabs(nums[l])<abs(nums[r]):r-=1else:l+=1iffound:returnreselse:return-1