imashutosh51

K Max Sum Combinations

Aug 5th, 2022 (edited)
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.32 KB | None | 0 0
  1. '''
  2. After sorting both arrays, the largest possible sum is always formed by the last elements, so we start from that pair. From any chosen pair (i, j), the only next possible better candidates are (i-1, j) and (i, j-1), because decreasing either index gives the next largest sums. We use a max heap to always pick the current largest sum and a visited set to avoid repeating the same index pairs until we collect the top k sums.
  3. '''
  4.  
  5. from heapq import heappush,heappop
  6. class Solution:
  7.     def topKSumPairs(self, a, b, k):
  8.         a.sort()
  9.         b.sort()
  10.        
  11.         i,j=len(a),len(b)
  12.         visited=set()
  13.         heap=[]
  14.        
  15.         visited.add((i-1,j-1))
  16.         last_sum=a[i-1]+b[j-1]
  17.         heappush(heap,(-last_sum,(i-1,j-1)))
  18.         ans=[]
  19.        
  20.         while len(heap)>0 and len(ans)<k:
  21.             temp=heappop(heap)
  22.             val=-temp[0]
  23.             ans.append(val)
  24.             i,j=temp[1][0],temp[1][1]
  25.            
  26.             if (i-1,j) not in visited:
  27.                 cur_sum=a[i-1]+b[j]
  28.                 heappush(heap,(-cur_sum,(i-1,j)))
  29.                 visited.add((i-1,j))
  30.             if (i,j-1) not in visited:
  31.                 cur_sum=a[i]+b[j-1]
  32.                 heappush(heap,(-cur_sum,(i,j-1)))
  33.                 visited.add((i,j-1))
  34.         return ans
  35.            
  36.        
  37.        
Advertisement
Add Comment
Please, Sign In to add comment