2
def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:4
# store the mxn size of the matrix8
dp = defaultdict(defaultdict)10
# Sorting each row of the array for more efficient pruning11
# Note:this purely based on the observation on problem constraints (although interesting :))13
mat[i] = sorted(mat[i])15
# returns minimum absolute starting from from row i to n-1 for the target16
globalMin = float("inf")18
def findMinAbsDiff(i, prevSum):21
globalMin = min(globalMin, abs(prevSum - target))22
return abs(prevSum - target)25
# because the array is increasing & prevSum & target will always be positive26
if prevSum - target > globalMin:29
if (i in dp) and (prevSum in dp[i]):32
minDiff = float("inf")33
# for each candidate select that and backtrack35
diff = findMinAbsDiff(i + 1, prevSum + mat[i][j])36
# pruning step 2 - break if we found minDiff 0 --> VERY CRTICIAL40
minDiff = min(minDiff, diff)42
dp[i][prevSum] = minDiff45
return findMinAbsDiff(0, 0)