Deloitte | COGNIZANT | IBM | CAPGEMINI
def getMaximumSum(matrix, k):
global idx
import heapq
from collections import deque
n = len(matrix)
rows = [deque(row) for row in matrix]
heap = []
for i in range(n):
if rows[i]:
heapq.heappush(heap, (-rows[i][0], i, True))
heapq.heappush(heap, (-rows[i][-1], i, False))
ans= 0
for _ in range(k):
while heap:
val, idx, is_left = heapq.heappop(heap)
if rows[idx]:
if is_left and rows[idx][0] == -val:
ans += rows[idx].popleft()
break
elif not is_left and rows[idx][-1] == -val:
ans += rows[idx].pop()
break
if rows[idx]:
heapq.heappush(heap, (-rows[idx][0], idx, True))
heapq.heappush(heap, (-rows[idx][-1], idx, False))
return ans
getMaximumSum✅✅
CISCO✅
985 ·