question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
minimize-the-difference-between-target-and-chosen-elements
c++ bitset. meh...
c-bitset-meh-by-0xffffffff-agsj
p is the bitset from 0 to 5000 (big enough) if the bit i is set, which means i can be the sum result by far, and do it row by row. \n\n\nclass Solution {\npubli
0xffffffff
NORMAL
2021-08-22T04:03:37.132860+00:00
2021-08-22T04:13:59.217133+00:00
6,026
false
p is the bitset from 0 to 5000 (big enough) if the bit `i` is set, which means `i` can be the sum result by far, and do it row by row. \n\n```\nclass Solution {\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n bitset<5000> p(1);\n for (auto& r : mat) {\n bitset<5000> tmp;\n for (auto& i : r) {\n tmp = tmp | (p << i);\n }\n swap(p,tmp);\n }\n int res = 10000;\n for (int i = 0; i < 5000; ++i) {\n if (p[i]) res = min(res, abs(i - target));\n }\n return res;\n }\n};\n```
72
5
[]
23
minimize-the-difference-between-target-and-chosen-elements
c++ solution using dp and memoization
c-solution-using-dp-and-memoization-by-d-e3gz
https://leetcode.com/problems/cherry-pickup/\n similar problem\n\nclass Solution \n{\npublic:\n int dp[8000][71];\n int n,m;\n int find(vector<vector<i
dilipsuthar17
NORMAL
2021-08-22T06:02:21.135283+00:00
2022-01-20T08:45:24.992519+00:00
8,320
false
[https://leetcode.com/problems/cherry-pickup/](http://)\n similar problem\n```\nclass Solution \n{\npublic:\n int dp[8000][71];\n int n,m;\n int find(vector<vector<int>>&mat,int r,int sum,int &target)\n {\n if(r>=n)\n {\n return abs(sum-target);\n }\n if(dp[sum][r]!=-1)\n {\n return dp[sum][r];\n }\n int ans=INT_MAX;\n for(int i=0;i<m;i++)\n {\n ans=min(ans,find(mat,r+1,sum+mat[r][i],target));\n if(ans==0)\n {\n break;\n }\n }\n return dp[sum][r]=ans;\n }\n int minimizeTheDifference(vector<vector<int>>& mat, int target) \n {\n memset(dp,-1,sizeof(dp));\n n=mat.size();\n m=mat[0].size();\n return find(mat,0,0,target);\n }\n};\n```
52
5
['Dynamic Programming', 'Memoization', 'C', 'C++']
11
minimize-the-difference-between-target-and-chosen-elements
[JAVA] DP Memoization
java-dp-memoization-by-grvk28-xwn9
Straightforward memoization solution\n\n\n\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n Integer[][] dp = new Inte
grvk28
NORMAL
2021-08-22T05:11:22.586689+00:00
2021-08-22T05:11:58.265553+00:00
4,705
false
Straightforward memoization solution\n\n\n```\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n Integer[][] dp = new Integer[mat.length][5001];\n return minDiff(mat, 0, target,0, dp);\n }\n \n public int minDiff(int[][] mat,int index,int target, int val, Integer[][] dp){\n if(index == mat.length){\n return Math.abs(val - target);\n }\n if(dp[index][val] != null){\n return dp[index][val];\n }\n \n int res = Integer.MAX_VALUE;\n for(int i = 0; i < mat[0].length; i++){\n res = Math.min(res, minDiff(mat, index + 1, target, val + mat[index][i], dp));\n }\n \n return dp[index][val] = res;\n }\n}\n```
48
0
['Dynamic Programming', 'Memoization', 'Java']
8
minimize-the-difference-between-target-and-chosen-elements
Thought Process || C++ || DP + Memoization || Explanation
thought-process-c-dp-memoization-explana-7u9e
If this helped you in anyway, please consider giving an UPVOTE\n\nIntution :\n\n Looking at the constraints we can surely think of a brute force approach, which
i_quasar
NORMAL
2021-09-10T15:45:39.305396+00:00
2021-09-10T15:45:39.305443+00:00
3,396
false
**If this helped you in anyway, please consider giving an UPVOTE**\n\n**Intution :**\n\n* Looking at the constraints we can surely think of a brute force approach, which we can later optimize. \n* Now, in the question we are asked to pick a element from each row and find the total sum. Then, out of all possible combinations, we have to return the one whose absolute difference with target is minimum. \n\t* i.e abs(target - sum) is minimum\n\t* Also, sum can be *greater than or less than* target\n\nLets see what we need to find. In these type of problems where we need to find all the possible combinations, try to solve it recusively by formulating a **recursive formula**. \n\n\tminAbsoluteDiff = min({all possbile sums}) -> there can be n^m possible sums.\n\t\nSo, we need to start picking every element for each row and add it to current path sum, and get the sum. And recursively call for next row along with path sum.\n\t\n\t\tsolve(mat, idx+1, sum+mat[idx][j], target)\n \n\t\nIn the end (base case) when we reach `(i == n)`, simply return absolute difference of target with sum. \n\nAlso, we need to memoize. It is simple, we just take a dp table. Since here sum and idx(index) are the 2 changing states. So we take `dp[][]`.\n\n# Code:\n\n```\nclass Solution {\npublic:\n int m, n;\n int dp[72][5000];\n int solve(vector<vector<int>>& mat, int row, int sum, const int& target)\n {\n\t\t// Base condition\n if(row == m)\n {\n return abs(sum - target);\n }\n \n\t\t// Check if already calculated\n if(dp[row][sum] != -1) return dp[row][sum];\n \n int minDiff = INT_MAX;\n for(int i=0; i<n; i++)\n {\n minDiff = min(minDiff, solve(mat, row+1, sum+mat[row][i], target));\n }\n return dp[row][sum] = minDiff;\n }\n \n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n m = mat.size();\n n = mat[0].size();\n memset(dp, -1, sizeof(dp));\n return solve(mat, 0, 0, target);;\n }\n};\n```
44
3
['Dynamic Programming', 'Memoization', 'C']
5
minimize-the-difference-between-target-and-chosen-elements
✅ 100% efficient | Pruning + Memoization | Dynamic Programming | Explanation
100-efficient-pruning-memoization-dynami-am3b
Explanation:\n\n\nPlease note following important observations from question,\n1. We must choose exactly one element from each row\n2. Minimize the diff between
captainx
NORMAL
2021-08-22T04:02:31.696345+00:00
2021-08-22T13:11:54.033054+00:00
3,976
false
**Explanation:**\n\n\nPlease note following important observations from question,\n1. We must choose exactly one element from each row\n2. Minimize the diff between target and the sum of all chosen elements\n\nApproach (and how to solve TLE)\n\nNow, the general idea is to explore all possibilities, however, that\'ll be very hug (~70^70). Hence, the immediate thought is to apply dynamic programmic. The subproblems can be modelled as,\n\n`findMinAbsDiff(i,prevSum)` -> returns the minimum abs diff with target, given that we\'re currently at row i and the sum of chosen numbers for row 0 to i-1 is `prevSum`\n\nHence, we can use a `dp[i][prevSum]` array for memoization. However, the answer will still not get accepted due to the nature of input test cases provided.\n\nSo, to optimize further you can leverage the fact the minimum possible answer for any input is `0`. Hence, if we get `0` absolute difference then we don\'t need to explore further, we stop and prune further explorations to save cost.\n\n**Additional Note:** I\'ve also sorted the array prior to actual exploration code to make pruning more efficient, based on the observation of the test constraints, as the target sum is much smaller compared to the sum of max values of the rows. However, that\'s not neccesary. \n\n**Code:**\n```\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n \n # store the mxn size of the matrix\n m = len(mat)\n n = len(mat[0])\n \n dp = defaultdict(defaultdict)\n \n # Sorting each row of the array for more efficient pruning\n # Note:this purely based on the observation on problem constraints (although interesting :))\n for i in range(m):\n mat[i] = sorted(mat[i])\n \n # returns minimum absolute starting from from row i to n-1 for the target\n globalMin = float("inf")\n def findMinAbsDiff(i,prevSum):\n nonlocal globalMin\n if i == m:\n globalMin = min(globalMin, abs(prevSum-target))\n return abs(prevSum-target)\n \n # pruning step 1\n # because the array is increasing & prevSum & target will always be positive\n if prevSum-target > globalMin:\n return float("inf")\n \n \n if (i in dp) and (prevSum in dp[i]):\n return dp[i][prevSum]\n \n minDiff = float("inf")\n # for each candidate select that and backtrack\n for j in range(n):\n diff = findMinAbsDiff(i+1, prevSum+mat[i][j])\n # pruning step 2 - break if we found minDiff 0 --> VERY CRTICIAL\n if diff == 0:\n minDiff = 0\n break\n minDiff = min(minDiff, diff)\n \n dp[i][prevSum] = minDiff\n return minDiff\n \n return findMinAbsDiff(0, 0)\n```
30
1
['Dynamic Programming', 'Memoization', 'Python', 'Python3']
8
minimize-the-difference-between-target-and-chosen-elements
Java dp code with proper comments and explanation
java-dp-code-with-proper-comments-and-ex-2m2r
We can simply iterate over all the possible cases and memoise the already taken path to avoid repetitive calculation.\nDp with states as current row and sum til
Jay_Bisht
NORMAL
2021-08-22T04:01:29.037568+00:00
2021-08-22T04:01:29.037609+00:00
2,132
false
We can simply iterate over all the possible cases and memoise the already taken path to avoid repetitive calculation.\nDp with states as current row and sum till now would do it.\n```\n int ans = Integer.MAX_VALUE;\n boolean[][] dp; // For memoisation\n void func(int[][] mat , int r, int sum, int t){ // where dp states are current row and the sum achieved yet.\n if(dp[r][sum]) return; // If the same row has already been visited with the same sum no need to further process.\n if(r==mat.length-1){ // base case for the last row.\n for(int i=0;i<mat[0].length;i++){\n ans=Math.min(ans,Math.abs(sum+mat[r][i]-t));\n }\n dp[r][sum]=true; // processing done, so mark in the dp table\n return;\n }\n for(int i=0;i<mat[0].length;i++){ // Iterating over every possibility\n func(mat,r+1,sum+mat[r][i],t);\n }\n dp[r][sum]=true; //// processing done, so mark in the dp table\n }\n public int minimizeTheDifference(int[][] mat, int t) {\n dp = new boolean[mat.length][5000];\n func(mat,0,0,t);\n return ans;\n }\n
16
7
[]
4
minimize-the-difference-between-target-and-chosen-elements
from TLEs To getting Accepted | C++
from-tles-to-getting-accepted-c-by-spart-wuh3
Brute Force\nThe Brute Force Way of doing it is exploring all cells from each row and passing our decisions downwards.\n\nBase Case\nWhat if you have only 1 row
spartanleonidis
NORMAL
2021-08-22T04:28:10.281140+00:00
2021-09-04T08:13:45.496013+00:00
1,888
false
**Brute Force**\nThe Brute Force Way of doing it is exploring all cells from each row and passing our decisions downwards.\n\n***Base Case***\nWhat if you have only 1 row ? then you choose the cell which gives minimum difference with target\n\nBut this is going to get TLE:\n\n\n**Observation**\n\nNext step to a recursive code is to see if there are any repeated calls which can be stored.\n\nSo if we reach ith row with a sum=s which we had come earlier as well then decisions are going to be same here onwards. So we can create a 2D dp table of size ( rows * (all possible sums) ).\n\nNow what is the range of all possible sums ? we are choosing 1 element from each row and there are 70 rows and each element can have a max value of 70 so took max value of all possible sums = **(71x71)**\n\n\n**Another Observation:**:\nWe can eliminate same valued cells from each row as having multiple of them is not giving any new path.\n\n\n\n**Top Down Recursive Code With Memoisation**:\n\n```\nclass Solution {\npublic:\n \n\tint min_diff(vector<vector<int>> & mat,int row,int curr,int target,vector<vector<int>> & dp){\n\n\t\tint rows=mat.size();\n\t\tint cols=mat[row].size();\n\n\t\t // if know the answer for this already simply return \n\t\t if(dp[row][curr]!=-1){\n\t\t\treturn dp[row][curr];\n\t\t}\n\n\t\t// only one row left so take the one which gives minimum difference with target\n\t\tif(row==rows-1){\n\n\t\t\tint diff=INT_MAX;\n\t\t\tfor(int col=0;col<cols;col++){\n\t\t\t\tint cd=abs(target-(curr+mat[row][col]));\n\t\t\t\tdiff=min(diff,cd);\n\t\t\t}\n\n\t\t\t// remember the result\n\t\t\tdp[row][curr]=diff;\n\t\t\treturn diff;\n\t\t}\n\n\t\tint bdiff=INT_MAX;\n\t\tfor(int col=0;col<cols;col++){\n\t\t\t// pass on the choice to next row\n\t\t\tint cdiff=min_diff(mat,row+1,curr+mat[row][col],target,dp);\n\t\t\t// update if we get a better choice \n\t\t\tbdiff=min(bdiff,cdiff);\n\n\t\t\t// we can\'t have a better choice then this so stop here\n\t\t\tif(bdiff==0){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\n\t\tdp[row][curr]=bdiff;\n\t\treturn bdiff;\n\t}\n\n\tint minimizeTheDifference(vector<vector<int>>& mat, int target) {\n\n\tint rows=mat.size();\n\tint cols=mat[0].size();\n\n\t// grid with each row having unique values\n\tvector<vector<int>> grid;\n\n\tfor(int row=0;row<rows;row++){\n\t\tunordered_map <int,bool> unique; \n\t\tfor(int col=0;col<cols;col++){\n\t\t\tunique[mat[row][col]]=true;\n\t\t}\n\n\t\tvector<int> cr;\n\t\tfor(auto elem:unique){\n\t\t\tcr.push_back(elem.first);\n\t\t}\n\n\t\tgrid.push_back(cr);\n\t}\n\n\tvector<vector<int>> dp(rows,vector<int>(5041,-1));\n\tint ans=min_diff(grid,0,0,target,dp);\n\treturn ans;\n\t}\n};\n```\n\nTime Complexity -> **O(rows * columns * (all possible sums))**\nSpace Complxity -> **O(rows * (all possible sums))**\n\nI hope this was helpful!\nIf there are any suggestions or optimisations do tell. If this helped somehow do consider upvoting :) .
15
0
[]
3
minimize-the-difference-between-target-and-chosen-elements
Python [set]
python-set-by-gsan-hq4p
python\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n R, C = len(mat), len(mat[0])\n \n
gsan
NORMAL
2021-08-22T04:04:44.504384+00:00
2021-08-22T04:04:44.504411+00:00
1,358
false
```python\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n R, C = len(mat), len(mat[0])\n \n S = set(mat[0])\n for r in range(1, R):\n NS = set()\n for x in set(mat[r]):\n for y in S:\n NS.add(x + y)\n S = NS\n \n return min(abs(x - target) for x in S)\n```
14
0
[]
3
minimize-the-difference-between-target-and-chosen-elements
Simple C++ (Recursion + Memo)
simple-c-recursion-memo-by-mazhar_mik-nm6q
This solution was accepted earlier.\nAccepted:\n\n\n\nclass Solution {\npublic:\n int t[5001][71];\n int row, col;\n \n int find(vector<vector<int>>
mazhar_mik
NORMAL
2021-08-22T04:14:04.095739+00:00
2021-09-01T19:12:38.558961+00:00
1,088
false
This solution was accepted earlier.\nAccepted:\n![image](https://assets.leetcode.com/users/images/1142deb7-90af-4830-b69a-dba21cffbf0d_1629606425.2784035.png)\n\n```\nclass Solution {\npublic:\n int t[5001][71];\n int row, col;\n \n int find(vector<vector<int>>& mat, int row, int sum, int& target)\n {\n if(row <= 0)\n return abs(sum-target);\n \n if(t[sum][row]!=-1)\n return t[sum][row];\n \n int minDiff = INT_MAX;\n for(int j=0; j<col; j++)\n {\n minDiff = min(minDiff, find(mat, row-1, sum+mat[row-1][j], target));\n }\n return t[sum][row] = minDiff;\n }\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n memset(t,-1,sizeof(t));\n row = mat.size();\n col = mat[0].size();\n return find(mat, row, 0, target);\n \n }\n};\n```\n\n/*\nNow, the solution gives TLE as new test cases have been added. I will be updating this with an accepted approach. Thanks @user77777 for letting me know the latest update.\n*/
12
5
[]
4
minimize-the-difference-between-target-and-chosen-elements
Easy to Understand Java Solution with Explanation
easy-to-understand-java-solution-with-ex-3ud5
Sharing easy to understand solution using 2 sets.\n\nIdea:\n1) Brute Force (TLE): Create 2 sets (1 representing all the possible sums up to but not including th
simonzhu91
NORMAL
2021-08-22T04:27:36.129699+00:00
2021-08-22T04:30:42.023110+00:00
1,553
false
Sharing easy to understand solution using 2 sets.\n\nIdea:\n1) **Brute Force (TLE):** Create 2 sets (1 representing all the possible sums up to but not including the current row, 1 representing all the possible sums up to and including the current row). Iterate matrix row by row, for each element in set, column by column, and add each element to each possible sub-sum so far. Save all the possible sums to a new set and set the current to the new set at the end of a row. At the end, look in all the possible sums to find the closest one to target.\n2) **Optimization:** You actually don\'t need all the possible sums at each row, you really only need all sums up to the smallest sum that is greater or equal to target. So a small optimization is to remove all the sums that are greater than the smallest sum greater or equal to target.\n3) **Analysis:** Time Complexity: `O(target * m * n)`, Space Complexity: `O(target + n)`\n\n```\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n Set<Integer> s_curr = new HashSet<>();\n Set<Integer> s_new = new HashSet<>();\n s_curr.add(0);\n for (int i = 0; i < mat.length; i++) {\n s_new = new HashSet<>();\n for (Integer v : s_curr) {\n for (int j = 0; j < mat[i].length; ++j)\n s_new.add(v + mat[i][j]);\n }\n \n // Remove all elements greater than the smallest element greater than target\n int min_over = Integer.MAX_VALUE;\n for (Integer v : s_new) {\n if (v >= target) min_over = Math.min(min_over, v);\n }\n s_curr = new HashSet();\n for (Integer v : s_new) {\n if (v <= min_over) s_curr.add(v);\n }\n }\n int min_diff = Integer.MAX_VALUE;\n for(Integer v : s_curr){\n int curr_diff = Math.abs(v - target);\n min_diff = Math.min(curr_diff, min_diff);\n }\n return min_diff;\n }\n}\n```\n
11
0
[]
6
minimize-the-difference-between-target-and-chosen-elements
Python 3 || 4 lines, sets || T/S: 58% / 51%
python-3-4-lines-sets-ts-58-51-by-spauld-r872
\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n\n mat = [set(row) for row in mat]\n \n
Spaulding_
NORMAL
2023-02-12T19:41:30.028602+00:00
2024-06-22T22:01:23.054970+00:00
704
false
```\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n\n mat = [set(row) for row in mat]\n \n rSet = set(mat.pop())\n\n for row in mat: rSet = {m+n for m in row for n in rSet}\n \n return min(abs(n - target) for n in rSet)\n\n```\n[https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements/submissions/1297116967/](https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements/submissions/1297116967/)\n\nI could be wrong, but I think that time complexity is *O*(*MN* 2^*N*) and space complexity is *O*(2^*N*), in which *M* ~ `len(mat)` and *N* ~ `len(mat[0])`.\n
10
0
['Python3']
1
minimize-the-difference-between-target-and-chosen-elements
Simple DP Solution||C++
simple-dp-solutionc-by-rk_code-sa9l
\nclass Solution {\npublic:\n int dp[5001][71];\n int find(vector<vector<int>>& mat,int n,int sum,int tar)\n {\n if(n<=0)\n return ab
rk_code
NORMAL
2021-08-22T04:01:26.441098+00:00
2021-08-22T04:01:26.441135+00:00
999
false
```\nclass Solution {\npublic:\n int dp[5001][71];\n int find(vector<vector<int>>& mat,int n,int sum,int tar)\n {\n if(n<=0)\n return abs(sum-tar);\n if(dp[sum][n]!=-1)return dp[sum][n];\n \n int ans=INT_MAX;\n for(int j=0;j<mat[n-1].size();j++)\n {\n ans=min(ans,find(mat,n-1,sum+mat[n-1][j],tar));\n }\n return dp[sum][n]=ans;\n }\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n memset(dp,-1,sizeof(dp));\n return find(mat,mat.size(),0,target);\n \n }\n};\n```
9
7
[]
10
minimize-the-difference-between-target-and-chosen-elements
simple c++ memoization
simple-c-memoization-by-ranjan_1997-msta
\nclass Solution {\npublic:\n int pq[10000][100];\n int helper(vector<vector<int>>&mat,int row,int sum,int target)\n { \n if(row >= mat.size()
ranjan_1997
NORMAL
2021-08-23T06:03:43.570741+00:00
2021-08-23T06:03:43.570794+00:00
908
false
```\nclass Solution {\npublic:\n int pq[10000][100];\n int helper(vector<vector<int>>&mat,int row,int sum,int target)\n { \n if(row >= mat.size())\n return abs(sum-target);\n if(pq[sum][row] != -1)\n return pq[sum][row];\n int ans = INT_MAX;\n for(int i = 0;i<mat[row].size();i++)\n {\n ans = min(ans,helper(mat,row+1,sum+mat[row][i],target));\n }\n return pq[sum][row] = ans;\n }\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n memset(pq,-1,sizeof(pq));\n int n = mat.size();\n int m = mat[0].size();\n return helper(mat,0,0,target);\n \n }\n};\n```
8
1
[]
0
minimize-the-difference-between-target-and-chosen-elements
Python Set and Early Stop (2700ms)
python-set-and-early-stop-2700ms-by-john-y22t
\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n possibleSum = set([0])\n for m in mat:\n
johnnylu305
NORMAL
2021-08-22T04:31:22.566844+00:00
2021-08-22T04:31:22.566872+00:00
580
false
```\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n possibleSum = set([0])\n for m in mat:\n temp = set()\n for y in possibleSum:\n for x in sorted(set(m)):\n temp.add(x+y)\n if x+y>target:\n break\n possibleSum = temp\n return min(abs(s-target) for s in possibleSum)\n```
7
1
['Python']
2
minimize-the-difference-between-target-and-chosen-elements
Simple C++ Bottom Up Approach O(n*m*target)
simple-c-bottom-up-approach-onmtarget-by-g12w
\n\nclass Solution {\npublic:\n \n int m, n;\n \n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n \n m = mat.size(
akshitgarg09
NORMAL
2021-08-22T04:12:38.056514+00:00
2021-08-22T04:15:37.405029+00:00
1,332
false
```\n\nclass Solution {\npublic:\n \n int m, n;\n \n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n \n m = mat.size();\n n = mat[0].size();\n \n vector<vector<int>> dp(m+1, vector<int>(target+1, INT_MAX));\n \n // dp[i][j] ans for upto ith row and j target val\n \n for(int j=0; j<=target; j++) dp[0][j] = j;\n \n for(int i=1; i<=m; i++){\n for(int j=0; j <= target; j++){\n for(int k=0; k<n; k++){\n if(j >= mat[i-1][k]) dp[i][j] = min(dp[i][j], dp[i-1][j - mat[i-1][k]]);\n else dp[i][j] = min(dp[i][j], (mat[i-1][k] - j) + dp[i-1][0]);\n }\n }\n }\n \n int ans = dp[m][target];\n \n return ans;\n }\n};\n```
7
1
['Dynamic Programming', 'C', 'C++']
2
minimize-the-difference-between-target-and-chosen-elements
Bit-Manipulation (Bitset)|| Meet in the Middle || C++ ||
bit-manipulation-bitset-meet-in-the-midd-1rk9
Intuition\n Describe your first thoughts on how to solve this problem. \nPoints to Notice:-\n\nQuestion 1755 - https://leetcode.com/problems/closest-subsequence
intern_grind
NORMAL
2023-06-15T06:12:18.852841+00:00
2023-06-15T07:10:23.949729+00:00
151
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nPoints to Notice:-\n\nQuestion 1755 - [https://leetcode.com/problems/closest-subsequence-sum/]()\nQuestion 2035 - [https://leetcode.com/problems/partition-array-into-two-arrays-to-minimize-sum-difference/]()\n\nIn these two questions, MEET IN THE MIDDLE techniques were used and not Dp because sum could be negative and it is not feasible to represent negative sum in dp indices [Although what if we try shifting the nums vector and try!! Could be tried].\n\nSo we used Meet in the middle concept.\nBut here, we can see the constraints and notice sum, will never be negative and we can apply Dp.\n\nWe do not worry if there are multiple ways to reach an index with an particular previous sum, we are not counting number of ways, so we can count it as overlapping subproblem and continue solving using DP.\n\nWith Dp, comes an auxillary stack space.\nSO trying Bitmanipulation technique, which is very interesting using Bitset\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMaximum possible sum of the grid is 70*70 i.e. 4900. We still create a bitset of 5000 size.\n\nSo bitset<10>bt means $0 0 0 0 0 0 0 0 0 0$ bits and if i do bt[0] will tell be about the 0th bit. \n\nSo if at some point bistet<10> bt = 0 0 0 0 0 0 1 1 1 0. So, now bt[2] will give 1.\n\nIn our question, our idea is to use bitset to tell which sums are possible.\nIf sum x is possible we make bit[x] as 1.\n\nNow, question is how to find all possible x. We can find is using Recurssion only. Yes but using bit techniques it is also possible.\n\nFirst we put the first row in our final bitset. So now we know which sums are possible. \n\nFor example if first row is [3,4,8] so not bt[3]==bt[4]==bt[8]==1.\n\nNow for every remainning row, we run it on a loop\nlet\'s say we are at $i^{th}$ row and the previoud bitset we got is $bt$.\n\nWe make two temp bitset such as $prev = bt$ && a new bitset nxt.\n\nNow for every element in the $i^{th}$ row , we shift the prev to left by that element.\n\nFor example the value is 5. We shift prev bitset by 5 and update the next bitset by keep taking OR with shifted prev.\n\nSo if prev == 0 0 0 0 0 0 1 1 1 0 0 1 0 0 1\nNow it means we have already encountered sum = $0,3,6,7,8$.\nNow if we get mat[i][j]=5. It means next is 5. So now we add it to all elements of prev and update. Or we can just left shift by 5. \n\nprev <<5 becomes = 0 0 0 0 0 0 1 1 1 0 0 1 0 0 1 0 0 0 0 0\n\nSo it means the encountered sum = $5,8,11,12,13$\n\nNow we keep taking OR and in the end of $i^{th}$ row we update the bt with nxt as nxt stored the permutations \n\nIn the end, if the $i^{th}$ is 1, it means we have encountered i sum. So we can check.\n\n\n\nOne of the big reasons we are using this is because the sum is very less and bitset can be used.\n\nIf question asked us to find all sum of all subsets in a nums, we can apply same approach in that question too. Insert 0 in bitset and keep taking or with left shifted bitset with that nums[0] onwards. But in these the sum possible becomes $10^9$. So it becomes infeasible.\nWe can do this in this question.\n\n[https://leetcode.com/problems/partition-equal-subset-sum/description/]()\n\n \n\n# Complexity\n- Time complexity: Final TC - $O(n)$ + $O(maxSUM)*[1+2*m+m*n]$\n- Or - $m*n*maxsum$ \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(max_sum)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeTheDifference(vector<vector<int>>&mat, int target) \n {\n std::ios_base::sync_with_stdio(false); \n cin.tie(NULL); \n cout.tie(NULL);\n \n \n int m = mat.size();\n int n = mat[0].size(); \n bitset<5000>bt; \n for(int i =0;i<n;i++) bt[mat[0][i]]=1; // O(n) \n for(int i =1;i<m;i++) // O(m) \n {\n bitset<5000>prev = bt; // O(max_sum) \n bitset<5000>nxt; \n for(int j =0;j<n;j++) //O(n)\n {\n nxt = nxt | (prev<<mat[i][j]); // O(max_sum)\n }\n bt = nxt; // O(max_sum) \n }\n int ans=INT_MAX; \n for(int i =0;i<(5000);i++) // O(max_sum) \n {\n if(bt[i]) \n {\n ans=min(ans, abs(i-target)); \n }\n }\n return ans; \n\n }\n};\n\n\n```
5
0
['Bit Manipulation', 'Bitmask', 'C++']
1
minimize-the-difference-between-target-and-chosen-elements
python dp using @cache
python-dp-using-cache-by-takaos-0xk8
\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n m = len(mat)\n \n for i in range(m):\n
takasoft
NORMAL
2021-08-22T05:01:34.265857+00:00
2021-08-22T05:02:01.448209+00:00
912
false
```\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n m = len(mat)\n \n for i in range(m):\n mat[i] = set(mat[i]) # remove duplicates\n \n self.min_diff = inf\n \n @cache\n def search(i, s):\n if target + self.min_diff < s: # sum is too big\n return inf\n if i == m:\n return abs(target-s)\n \n row = mat[i]\n min_diff = inf\n for num in row:\n min_diff = min(min_diff, search(i+1, s + num))\n \n self.min_diff = min(self.min_diff, min_diff)\n \n return min_diff\n \n return search(0, 0)\n```
5
0
['Dynamic Programming', 'Python']
0
minimize-the-difference-between-target-and-chosen-elements
Python 3 - DP with Bit Masking
python-3-dp-with-bit-masking-by-yixianns-eh36
Intuition\nUpon first consideration, this problem resembles a variant of the knapsack problem, where we aim to find a combination of elements (one from each row
yixianns
NORMAL
2024-01-25T08:19:42.748426+00:00
2024-01-25T08:19:42.748447+00:00
267
false
# Intuition\nUpon first consideration, this problem resembles a variant of the knapsack problem, where we aim to find a combination of elements (one from each row of the matrix) that sums up as close as possible to a given target. A direct approach would be to enumerate all possible combinations, but that would be inefficient. Instead, we can use dynamic programming to efficiently track all possible sums up to a certain row and then find the closest sum to the target.\n\nThe most efficient way to perform dynamic programming in this case is to keep track of this is via bit masking.\n\n**Understanding the Bitmask (seen)**\n\nThe variable seen is a bitmask where each bit represents whether a particular sum is achievable. For example, if the 3rd bit in seen is 1 (...001000 in binary) (Note: 0-th index), it means a sum of 3 is achievable with the selected elements.\n\n**The setup**\nInitially, seen is set to 1 (...0001 in binary), indicating that a sum of 0 is achievable (since no elements have been selected yet).\n\n**Updating the Bitmask**\nFor each row in the matrix, the algorithm updates the seen bitmask to include new sums that can be achieved by adding each element of the current row to the sums represented in seen.\n\n**How Bit Shifting (<<) Works in This Context**\nThe operation seen << num shifts all bits in seen to the left by num positions. In terms of sums, this is equivalent to adding num to each of the sums represented by the set bits in seen.\n\nFor example, if seen is ...00101 (representing sums 0 and 2), and num is 3, then seen << num results in ...101000, representing sums 3 and 5.\n\n**Combining Sums with Bitwise OR (|=)**\nThe operation new_seen |= seen << num is used to combine the new sums generated by adding num to the existing sums in seen.\nThe bitwise OR (|) operation merges the two sets of sums (the original sums and the new sums after adding num).\nThis step ensures that new_seen includes all possible sums that can be made by picking any one element from the current row and adding it to the sums that were already achievable from the previous rows.\n\n**Example**\nSuppose seen initially represents sums [0, 2] (...00101 in binary).\nThe current row of the matrix is [3, 4].\nFor num = 3, seen << 3 becomes ...101000 (representing sums [3, 5]).\nThe operation new_seen |= ...101000 updates new_seen to include these new sums.\nThe process repeats for num = 4, and so on for each element in the row.\n\n**Final answer**\nTo obtain the final answer, we being searching from target and expanding outwards. \n\nTo prevent negative shift values, we perform the loop again once the index is larger than the index. \n\n# Code\n```\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n seen = 1\n for row in mat:\n new_seen = 0\n for num in set(row):\n new_seen |= seen << num\n seen = new_seen\n\n for i in range(target):\n if seen & (1<<target + i | 1<<target - i):\n return i\n \n for i in range(target, 4901): # 70 * 70 + 1:\n if seen & 1<<target + i:\n return i\n```\n\n![image.png](https://assets.leetcode.com/users/images/04648cf3-bfae-4c1d-87c3-3151e1d01cac_1706170702.709449.png)\n
4
0
['Python3']
1
minimize-the-difference-between-target-and-chosen-elements
✅Accepted || ✅Short & Simple || ✅Best Method || ✅Easy-To-Understand
accepted-short-simple-best-method-easy-t-od2x
\n# Code\n\nclass Solution {\npublic:\n int m, n;\n int dp[70*70+1][70];\n int dfs(vector<vector<int>>& mat, int r, int sum, int target)\n {\n
sanjaydwk8
NORMAL
2023-01-29T08:28:02.460794+00:00
2023-01-29T08:28:02.460829+00:00
831
false
\n# Code\n```\nclass Solution {\npublic:\n int m, n;\n int dp[70*70+1][70];\n int dfs(vector<vector<int>>& mat, int r, int sum, int target)\n {\n if(r>=m)\n return abs(sum-target);\n if(dp[sum][r]!=-1)\n return dp[sum][r];\n int ans=INT_MAX;\n for(int i=0;i<n;i++)\n {\n ans=min(ans, dfs(mat, r+1, sum+mat[r][i], target));\n if(ans==0)\n break;\n }\n return dp[sum][r]=ans;\n }\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n memset(dp,-1,sizeof(dp));\n m=mat.size();\n n=mat[0].size();\n return dfs(mat, 0, 0, target);\n }\n};\n```\nPlease **UPVOTE** if it helps \u2764\uFE0F\uD83D\uDE0A\nThank You and Happy To Help You!!
4
0
['C++']
1
minimize-the-difference-between-target-and-chosen-elements
C++, using bitset in O(1) space
c-using-bitset-in-o1-space-by-roshan_186-t4r0
Intuition\n->1st observation is that sum <= 70 * 70 \n->2nd obserbation is that to reduce space complexity (solution with dp have same complexity of O(500071))
Roshan_1860
NORMAL
2023-01-28T08:23:05.076567+00:00
2023-01-28T08:24:40.992840+00:00
197
false
# Intuition\n->1st observation is that sum <= 70 * 70 \n->2nd obserbation is that to reduce space complexity (solution with dp have same complexity of O(5000*71)) we have to use something that can tell in linear time that if this sum is possible or not. so bitset<> is best for that \n\n# Approach\n1. First row values mat[0][j] can be possible sums so will set the bit of possible sum on that index (eg. mat[0][0] = 4 so possible_sum = 00......00100)\n2. iterate on each element of every row \n3. intialize bitset<>on_that_row = possibel_sum(bitset from previous row)\n4. now left shift operation: (prev << mat[i][j]). this will left shift the bitset<> previous row it same like addition of two number\n(eg. bitst<>prev = 00......0010100 means upto previous row sum = 2 and sum = 4 are possibe now let mat[next_row][0] = 2 so will left shift two times the previous row bitset so on_that_row = 0000...01010000 means on this row possible sums = 4 and sum = 6) ,now for all sum will do OR operation\n5. now again for each row update the possible_sum by on_that_row.\n6. now just check set bit in possible_sum and check for result.\n\n\nIf u have any doubt feel free to ask in comments section, hope u liked the solution.\n\n# Complexity\n- Time complexity:\n$$O(n*m)$$\n\n- Space complexity:\n$$O(1)$$ \n\n# Code\n```\nclass Solution {\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) \n {\n\n int m = mat.size(), n = mat.front().size(), cs = 5000, res = cs;\n bitset<5000> possible_sum;\n for(int i=0; i<n; ++i) possible_sum[mat[0][i]] = 1;\n for(int i=1; i<m; ++i) {\n bitset<5000> pre = possible_sum, on_that_row;\n for(int j=0; j<n; ++j) {\n on_that_row |= (pre << mat[i][j]);\n }\n possible_sum = on_that_row;\n }\n for(int i=0; i<cs; ++i) {\n if(possible_sum[i]) res = min(res, abs(i-target));\n }\n return res;\n }\n};\n```
4
0
['Bit Manipulation', 'C++']
1
minimize-the-difference-between-target-and-chosen-elements
[Java] Short and Concise DP-Memoize solution
java-short-and-concise-dp-memoize-soluti-zb9j
Logic : Create a 2-D dp array with dimesions row*(max sum possible) . Traverse through each path possible from first row to last row taking one element form eac
chemEn
NORMAL
2021-08-22T04:10:05.096102+00:00
2021-08-22T18:02:14.223000+00:00
766
false
Logic : Create a 2-D dp array with dimesions row*(max sum possible) . Traverse through each path possible from first row to last row taking one element form each row . \n\n```\nclass Solution {\n\n int[][] dp;\n public int minimizeTheDifference(int[][] mat, int target) {\n dp=new int[mat.length][4901];\n for(int i=0;i<mat.length;i++) Arrays.fill(dp[i],-1);\n return dfs(mat,0,target,0);\n }\n public int dfs(int[][] mat,int index,int target,int sum){\n if(index==mat.length){\n return Math.abs(sum-target);\n }\n if(dp[index][sum]!=-1) return dp[index][sum];\n int ans=Integer.MAX_VALUE;\n for(int i=0;i<mat[0].length;i++){\n ans=Math.min(ans,dfs(mat,index+1,target,sum+mat[index][i]));\n }\n dp[index][sum]=ans;\n return ans;\n }\n}\n```
4
0
['Java']
1
minimize-the-difference-between-target-and-chosen-elements
DP memoization || Easy to understand || C++
dp-memoization-easy-to-understand-c-by-p-uruf
\nclass Solution {\npublic:\n int dp[71][5701];\n int minDiff(vector<vector<int>>& mat,int ind,int sum){\n if(ind==mat.size())return abs(sum);\n
praveen1208
NORMAL
2021-08-22T04:06:34.080252+00:00
2024-08-31T18:17:23.167654+00:00
661
false
```\nclass Solution {\npublic:\n int dp[71][5701];\n int minDiff(vector<vector<int>>& mat,int ind,int sum){\n if(ind==mat.size())return abs(sum);\n \n if(dp[ind][4900+sum]!=-1) return dp[ind][4900+sum];\n int res=INT_MAX;\n for(int i=0;i<mat[0].size();i++){\n res=min(res,minDiff(mat,ind+1,sum-mat[ind][i]));\n }\n \n return dp[ind][4900+sum]=res;\n }\n \n int minimizeTheDifference(vector<vector<int>>& Mat, int t) {\n int n=Mat.size(),m=Mat[0].size();\n \n if(n==1&&m==1)return abs(Mat[0][0]-t);\n \n for(int i=0;i<=n;i++){\n for(int j=0;j<=5700;j++){\n dp[i][j]=-1; \n } }\n \n int ans=minDiff(Mat,0,t);\n \n return ans;\n \n }\n};\n```\n\nQ: Why are we using 4900+sum?\nans: Actually min value of sum can be -4900+1,when each element of mat is 70 , max 70 row can exist and min value of traget is 1. So,min value of 4900+sum is always a +ve number .If we are not using this then -ve index of dp will give runtime error.\n\n
4
1
['Dynamic Programming', 'Memoization', 'C']
2
minimize-the-difference-between-target-and-chosen-elements
✅Clean DP Code || ⚡Memoization
clean-dp-code-memoization-by-adish_21-o2uo
\n\n# Complexity\n\n- Time complexity:\nO(m * m * 70)\n\n- Space complexity:\nO(m * m * 70)\n\n\n# Code\n## Please Upvote if it helps\uD83E\uDD17\n\nclass Solut
aDish_21
NORMAL
2024-06-09T12:38:40.829197+00:00
2024-06-09T12:38:40.829222+00:00
385
false
\n\n# Complexity\n```\n- Time complexity:\nO(m * m * 70)\n\n- Space complexity:\nO(m * m * 70)\n```\n\n# Code\n## Please Upvote if it helps\uD83E\uDD17\n```\nclass Solution {\npublic:\n int dp[71][4901];\n int helper(int i, int m, int n, vector<vector<int>>& mat, int target, int curr_sum){\n if(i == m)\n return abs(target - curr_sum);\n if(dp[i][curr_sum] != -1)\n return dp[i][curr_sum];\n int mini = INT_MAX;\n for(int j = 0 ; j < n ; j++)\n mini = min(mini, helper(i + 1, m, n, mat, target, curr_sum + mat[i][j]));\n return dp[i][curr_sum] = mini;\n }\n\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n int m = mat.size(), n = mat[0].size(), mini = INT_MAX;\n memset(dp, -1, sizeof(dp));\n for(int j = 0 ; j < n ; j++)\n mini = min(mini, helper(1, m, n, mat, target, mat[0][j]));\n return mini;\n }\n};\n```
3
0
['Array', 'Dynamic Programming', 'Memoization', 'Matrix', 'C++']
0
minimize-the-difference-between-target-and-chosen-elements
Bitset Solution
bitset-solution-by-techtinkerer-bn9h
\nm=mat.size();\nn=mat[0].size();\n# Complexity\n- Time complexity:O(mn(maxSum/64))\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(maxSum)\
TechTinkerer
NORMAL
2024-06-09T10:38:26.915173+00:00
2024-06-09T10:38:26.915205+00:00
198
false
\nm=mat.size();\nn=mat[0].size();\n# Complexity\n- Time complexity:O(m*n*(maxSum/64))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(maxSum)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n bitset<4901> dp;\n dp[0]=1;\n\n for(auto &i:mat){\n bitset<4901> temp;\n\n for(auto &j:i){\n temp=(temp|(dp<<j));\n\n } \n dp=temp;\n }\n int ans=INT_MAX;\n for(int i=4900;i>=0;i--){\n if(dp[i]) ans=min(ans,abs(i-target));\n }\n\n return ans;\n }\n};\n```
3
0
['C++']
0
minimize-the-difference-between-target-and-chosen-elements
[C++] Simple C++ Code
c-simple-c-code-by-prosenjitkundu760-dkue
If you like the implementation then Please help me by increasing my reputation. By clicking the up arrow on the left of my image.\n\nclass Solution {\n int a
_pros_
NORMAL
2022-08-04T04:58:26.671030+00:00
2022-08-04T04:58:26.671075+00:00
772
false
# **If you like the implementation then Please help me by increasing my reputation. By clicking the up arrow on the left of my image.**\n```\nclass Solution {\n int ans = INT_MAX;\n void dfs(int x, int s, vector<vector<int>> &dp, vector<vector<int>>& mat, int target, int n, int m)\n {\n if(s-ans >= target) return;\n if(dp[x][s] != -1) return;\n if(x == n)\n {\n //cout << s << " ";\n ans = min(ans, abs(target-s));\n \n dp[x][s] = 1;\n return;\n }\n else\n {\n for(int j = 0; j < m; j++)\n {\n dfs(x+1, s + mat[x][j], dp, mat, target, n, m);\n }\n dp[x][s] = 1;\n }\n return;\n }\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n int n = mat.size(), m = mat[0].size();\n vector<vector<int>> dp(n+1, vector<int> (4000, -1));\n dfs(0, 0, dp, mat, target, n, m);\n return ans;\n }\n};\n```
3
1
['Dynamic Programming', 'Recursion', 'Memoization', 'C', 'C++']
2
minimize-the-difference-between-target-and-chosen-elements
[Python] BruteForce with memo
python-bruteforce-with-memo-by-artod-vg7q
The bruteforce solution here is just to calculate all possible sums and then find the best that gives minium absolut difference with target. \n\nIf we start ite
artod
NORMAL
2021-11-11T04:56:01.845335+00:00
2021-11-11T05:39:24.793647+00:00
291
false
The bruteforce solution here is just to calculate all possible sums and then find the best that gives minium absolut difference with `target`. \n\nIf we start iterating all possible combinations of elements in columns, that algorithm would take O(m^n) time. So we are trying to optimize it by iterating the matrix from the bottom (*PS.: Not necessery to go from bottom to up*) and storing partial sums from the current row to the last row in the set `allSum`. Every time we move to the higher row, we iterate over that row, and for each element iterate over all partial sums in the set and add it to that sums. Because `allSum` is a set, the repeated values will disapear and we will not need to iterate over the same values. But anyway, in worst case we are going to have space and time complexity O(m^n).\n\nTime: **O(m^n)**\nSpace: **O(m^n)**\n\nRuntime: 12868 ms, faster than **6.67%** of Python online submissions for Minimize the Difference Between Target and Chosen Elements.\nMemory Usage: 14.5 MB, less than **10.00%** of Python online submissions for Minimize the Difference Between Target and Chosen Elements.\n\n```\nclass Solution(object):\n def minimizeTheDifference(self, mat, target):\n """\n :type mat: List[List[int]]\n :type target: int\n :rtype: int\n """\n \n n, m = len(mat), len(mat[0])\n \n # find all possible sums\n\t\t# at the start it\'s just a last row of the matrix\n allSum = set(mat[n - 1])\n \n if n > 1: \n for i in range(n-2, -1, -1): # iterate from the last row to the first\n rowSums = set()\n \n for j in range(0, m): # iterate over all elements in the row\n rowSums.update([mat[i][j] + sum for sum in allSum])\n \n allSum = rowSums\n \n # find absolute min\n minAbs = float("inf")\n \n for sum in allSum:\n absDif = abs(sum - target)\n if (absDif < minAbs):\n minAbs = absDif\n \n return minAbs\n```
3
1
['Dynamic Programming', 'Memoization']
1
minimize-the-difference-between-target-and-chosen-elements
C++ Solution Using DP
c-solution-using-dp-by-ariyanlaskar-7wy4
\n int dp[5001][71];\n int minimizeTheDifference(vector<vector<int>>& mat,int target) {\n memset(dp,-1,sizeof(dp));\n int n=mat.size();\n
Ariyanlaskar
NORMAL
2021-10-24T10:53:02.702155+00:00
2021-10-24T10:53:02.702211+00:00
451
false
```\n int dp[5001][71];\n int minimizeTheDifference(vector<vector<int>>& mat,int target) {\n memset(dp,-1,sizeof(dp));\n int n=mat.size();\n return findmat(mat,0,0,target);\n }\n int findmat(vector<vector<int>>&mat,int i,int sum,int &target){\n if(i>=mat.size()){\n return abs(sum-target);\n }\n if(dp[sum][i]!=-1){\n return dp[sum][i];\n }\n int ans=INT_MAX;\n for(int j=0;j<mat[i].size();j++){\n ans=min(ans,findmat(mat,i+1,sum+mat[i][j],target));\n }\n return dp[sum][i]=ans;\n }\n```
3
2
['Dynamic Programming', 'Memoization']
0
minimize-the-difference-between-target-and-chosen-elements
[Python3] Fast Fourier Transform O(sum*log(sum)*m)
python3-fast-fourier-transform-osumlogsu-jram
Using FFT for faster Sumset, works only for small bounded values(in this question sum cannot exceed 4900).\n\nfrom numpy.fft import rfft, irfft\nclass Solution:
adihosapate
NORMAL
2021-08-22T04:36:21.782598+00:00
2021-08-22T04:46:17.036063+00:00
181
false
Using FFT for faster Sumset, works only for small bounded values(in this question sum cannot exceed 4900).\n```\nfrom numpy.fft import rfft, irfft\nclass Solution:\n \n \n def fftrealpolymul(self,arr_a, arr_b): #fft based real-valued polynomial multiplication\n L = len(arr_a) + len(arr_b)\n a_f = rfft(arr_a, L)\n b_f = rfft(arr_b, L)\n return irfft(a_f * b_f,L)\n\n def convolve_rows_between(self,mat,low,high):\n if low == high:\n res = [0]*71\n for num in mat[low]:\n res[num] = 1\n return res\n mid = (low+high)//2\n upper_half = self.convolve_rows_between(mat,low,mid)\n lower_half = self.convolve_rows_between(mat,mid+1,high)\n multiplied_result = self.fftrealpolymul(upper_half,lower_half)\n mask_list = [min(1,round(num)) for num in multiplied_result]\n return mask_list\n \n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n \n possible_sums = self.convolve_rows_between(mat,0,len(mat)-1)\n minDiff = 100000\n for i in range(len(possible_sums)):\n if possible_sums[i]!=0:\n minDiff = min(minDiff,abs(i-target))\n \n return minDiff\n```
3
0
[]
0
minimize-the-difference-between-target-and-chosen-elements
java easy to understand dp
java-easy-to-understand-dp-by-ratatat-rarn
\nclass Solution {\n int min=Integer.MAX_VALUE;\n boolean[][] dp;\n public int minimizeTheDifference(int[][] mat, int target) {\n dp = new boole
ratAtat
NORMAL
2021-08-22T04:14:53.728286+00:00
2021-08-22T04:14:53.728322+00:00
268
false
```\nclass Solution {\n int min=Integer.MAX_VALUE;\n boolean[][] dp;\n public int minimizeTheDifference(int[][] mat, int target) {\n dp = new boolean[mat.length][5000];\n backTrack(0,mat, target, 0);\n return min;\n }\n \n public void backTrack(int row, int[][] mat, int target, int currSum ) {\n if(row==mat.length) {\n if(Math.abs(target-currSum)<min)\n min = Math.abs(target-currSum);\n return;\n }\n \n for(int i=0; i<mat[0].length; i++) {\n int sumNow = currSum+mat[row][i];\n if(dp[row][sumNow])\n continue;\n dp[row][sumNow] = true;\n backTrack(row+1, mat, target, sumNow);\n }\n }\n}```
3
1
[]
2
minimize-the-difference-between-target-and-chosen-elements
✅✅✅100% working solution in java || dp || memoization✅✅
100-working-solution-in-java-dp-memoizat-hzi4
```\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int t) {\n int m= mat.length;\n int[][] dp= new int[m][5001];\n fo
sona_14_28
NORMAL
2023-03-25T10:44:50.125571+00:00
2023-03-25T10:44:50.125606+00:00
1,040
false
```\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int t) {\n int m= mat.length;\n int[][] dp= new int[m][5001];\n for(int i=0; i<m; i++){\n for(int j=0; j<5001; j++){\n dp[i][j]=-1;\n }\n }\n return solve(mat,dp,0,t,0);\n }\n \n public int solve(int[][] mat, int[][] dp, int ind, int t, int val){\n if(ind==mat.length){\n return Math.abs(t-val);\n }\n \n if(dp[ind][val]!=-1){\n return dp[ind][val];\n }\n \n int min= (int)(1e9);\n for(int i=0; i<mat[0].length; i++){\n min= Math.min(min, solve(mat,dp,ind+1,t,val+mat[ind][i]));\n }\n \n return dp[ind][val]= min;\n }\n}
2
0
['Dynamic Programming', 'Memoization', 'Java']
0
minimize-the-difference-between-target-and-chosen-elements
C++ simple solution
c-simple-solution-by-akshat0610-wvpx
\nclass Solution {\npublic:\n int dp[4901][71];\n int minimizeTheDifference(vector<vector<int>>& mat, int target) \n {\n //int fun(vector<vector
akshat0610
NORMAL
2022-10-15T06:11:58.671507+00:00
2022-10-15T06:11:58.671533+00:00
975
false
```\nclass Solution {\npublic:\n int dp[4901][71];\n int minimizeTheDifference(vector<vector<int>>& mat, int target) \n {\n //int fun(vector<vector<int>>&mat,int &target,int sum,int row);\n memset(dp,-1,sizeof(dp));\n int row=0;\n int sum=0;\n return fun(mat,target,sum,row);\n }\n int fun(vector<vector<int>>&mat,int &target,int sum,int row)\n {\n if(row >= mat.size())\n {\n return abs(target-sum);\t\n }\n\n if(dp[sum][row]!=-1)\n return dp[sum][row];\n\n int ans=INT_MAX; //final ans that we will return //ans-->9\n for(int i=0;i<mat[row].size();i++)\n {\n ans=min(ans,fun(mat,target,sum+mat[row][i],row+1));\n if(ans==0)\n {\n return dp[sum][row]=ans;\n }\n }\n return dp[sum][row]=ans;\n }\n};\n```
2
0
['Dynamic Programming', 'Depth-First Search', 'Recursion', 'Memoization', 'C', 'C++']
0
minimize-the-difference-between-target-and-chosen-elements
[Java] [DP] Clean Code
java-dp-clean-code-by-java-lang-goutam-kz9i
```\nclass Solution {\n \n int min = Integer.MAX_VALUE;\n\n public int minimizeTheDifference(int[][] mat, int target) {\n final int maxM = 70;\n
java-lang-goutam
NORMAL
2022-06-04T03:53:26.565449+00:00
2022-06-04T03:55:55.706488+00:00
247
false
```\nclass Solution {\n \n int min = Integer.MAX_VALUE;\n\n public int minimizeTheDifference(int[][] mat, int target) {\n final int maxM = 70;\n final int maxN = 70;\n boolean[][] dp = new boolean[mat.length][(maxM * maxN) + 1];\n helper(mat, target, dp, 0, 0); \n return min;\n }\n \n private void helper(int[][] mat, int target, boolean[][] dp, int row, int sum) {\n \n if (row == mat.length) {\n min = Math.min(min, Math.abs(target-sum));\n return;\n }\n \n if (dp[row][sum]) return;\n \n for (int i=0; i<mat[0].length; i++) {\n helper(mat, target, dp, row+1, sum + mat[row][i]);\n }\n \n dp[row][sum] = true;\n }\n}
2
0
['Memoization']
1
minimize-the-difference-between-target-and-chosen-elements
C++ || DP Solution
c-dp-solution-by-ashu_iitp-4he6
\nclass Solution {\npublic:\n \n int n,m,goal;\n \n int dp[71][4905];\n vector<int> v;\n \n int solve(vector<vector<int>>& mat,int i,int su
ashu_iitp
NORMAL
2022-04-01T19:32:46.066174+00:00
2022-04-01T19:32:46.066213+00:00
403
false
```\nclass Solution {\npublic:\n \n int n,m,goal;\n \n int dp[71][4905];\n vector<int> v;\n \n int solve(vector<vector<int>>& mat,int i,int sum)\n {\n if(i>=n) \n {\n //picking element from each row and taking abs diff of all possible path.\n return abs(sum-goal);\n }\n \n //since sum>=goal,so from ith row till last we will only pick min element from each bcz \n\t\t//adding other element only increase abs diff as all element are +ve. so add all min \n\t\t//element from ith till last row and take abs diff.\n if(sum>=goal) return abs(sum+v[i]-goal);\n \n if(dp[i][sum]!=-1) return dp[i][sum]; \n \n int ans=INT_MAX;\n \n for(int j=0;j<m;j++)\n {\n ans=min(ans,solve(mat,i+1,sum+mat[i][j]));\n }\n \n return dp[i][sum]=ans;\n }\n \n \n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n \n n=mat.size(),m=mat[0].size();\n goal=target;\n \n for(auto &x:mat)\n {\n v.push_back(*min_element(begin(x),end(x)));//stores min element of each row\n }\n \n //v[i] now stores sum of min element of each row from i till last row\n for(int i=n-2;i>=0;i--) v[i]+=v[i+1];\n \n memset(dp,-1,sizeof(dp));\n \n return solve(mat,0,0);\n \n }\n};\n```
2
0
[]
1
minimize-the-difference-between-target-and-chosen-elements
illustrated explanation
illustrated-explanation-by-wilmerkrisp-ww0i
<-- please vote\n\n\n\n def minimizeTheDifference1(self, mat, target):\n nums = {0}\n [nums := {x + sx for x in row for sx in nums} for row in
wilmerkrisp
NORMAL
2022-02-24T18:21:53.184047+00:00
2022-02-24T18:21:53.184075+00:00
159
false
<-- please vote\n\n![image](https://assets.leetcode.com/users/images/1daca118-d4f3-442e-b20a-98cfb90ba368_1645726902.1581254.png)\n\n def minimizeTheDifference1(self, mat, target):\n nums = {0}\n [nums := {x + sx for x in row for sx in nums} for row in mat]\n return min(abs(target - x) for x in nums)
2
2
['Math', 'Python']
2
minimize-the-difference-between-target-and-chosen-elements
Easy C++ SOL using DP
easy-c-sol-using-dp-by-rashmimishra20156-xpxr
The question states that we need to pick one element from each row , such that \nthe absolute differnce b/w the sum and target is minimized. In other words, th
rashmiMishra20156
NORMAL
2022-02-08T19:17:03.441757+00:00
2022-02-08T19:17:03.441804+00:00
399
false
The question states that we need to pick one element from each row , such that \nthe absolute differnce b/w the sum and target is minimized. In other words, their sum should be close to target.\n\nSimple approach is try all possible combinatoins /paths, return the minimum value of abs(target-sum).\nHere , our result does not depend upon which column we are landing in. It depends upon the row to be traversed , and the target remaining / or say sum of chosen values upto that row.\n\nSo , let f(row, sum) be a function, which determines the total sum of chosen elements (one from each row) upto row th row from last row.\n\nf(row, sum)= min of( f(row-1, sum\'), f(row-1, sum\'\').........)\n![image](https://assets.leetcode.com/users/images/1912072e-f0da-4494-9345-afbfdc10c49a_1644347575.3780317.jpeg)\n\nThe above diagram shows that we ahve overlapping subprobelms , hence optimization can be done using dp.\n\n**Base case**- When row becomes 0 , that means we have included values from all rows to sum , hence we will return absolute difference of sum and target.\n\n**Points to remember**- Since the dp array , has row of mat as its row , so max size of row can be m+1, but the columns of dp array is sum , and the maximum value of sum can be 70*70 , hence we will initialise dp[m][4900+1]\n\n\n```\nint minDiff(int row,int n, vector<vector<int>>&mat, int target,int sum,vector<vector<int>>&dp){\n if(row==0)return dp[0][sum]=abs(target-sum);\n \n if(dp[row][sum]!=-1)return dp[row][sum];\n int diff=INT_MAX;\n for(int i=0;i<n;i++){\n int curr=minDiff(row-1,n,mat,target,sum+mat[row-1][i],dp);\n if(curr==0)return dp[row][sum]=0;\n diff=min(diff,curr);\n }\n return dp[row][sum]=diff;\n} \nclass Solution {\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n \n int m=mat.size();\n int n=mat[0].size();\n \n vector<vector<int>>dp(m+1,vector<int>(4900+2,-1));\n int sum=0;\n return minDiff(m,n,mat,target,sum,dp);\n }\n};\n\n\n\n\n
2
0
['Memoization', 'C']
1
minimize-the-difference-between-target-and-chosen-elements
56 ms, faster than 98.23% of Java DFS + memo solution
56-ms-faster-than-9823-of-java-dfs-memo-h9w40
Time: n(mlogm + m) + 2^(nm)\nSpace: n* target\n\n\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n //1. Prepare proc
anquan
NORMAL
2021-09-12T21:20:17.465874+00:00
2021-09-12T21:21:31.713490+00:00
210
false
Time: n*(mlogm + m) + 2^(n*m)\nSpace: n* target\n\n```\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n //1. Prepare process\n int remain = target;\n for (int i = 0; i < mat.length; i++) {\n\t\t\tArrays.sort(mat[i]); //1) sort each row\n \n int minValue = mat[i][0];\n remain -= minValue; //2) let remain=sum(min value per row)\n for (int j = 0; j < mat[i].length; j++) {\n mat[i][j] -= minValue; //3) rebase row so that can be used in dfs directly\n }\n }\n \n if (remain <= 0) {//stop when target <= sum of the min value in each row\n return Math.abs(remain);\n }\n \n\t\t//2. Cached version DFS\n //1) Cache calcuated result to avoid Time Limit Exceeded error\n\t\t//2) Saving space by using remain instead of target\n Integer[/*row*/][/*remain*/] memo = new Integer[mat.length][remain + 1];\n \n return dfs(0, remain, memo, mat);\n }\n \n private int dfs(int row, int remain, Integer[][] memo, int[][] mat) {\n if (row >= mat.length || remain <= 0) {\n return Math.abs(remain);\n }\n \n if (memo[row][remain] != null) {\n return memo[row][remain];\n }\n \n int min = Math.abs(remain);\n \n\t\t//Take one item from current row then join with the rest of table\n //Start col from 0 means take the 1st column value\n for (int col = 0; col < mat[0].length; col++) {\n min = Math.min(min, dfs(row + 1, remain - mat[row][col], memo, mat));\n \n\t\t\tif (min == 0) {\n return 0; //early return\n }\n \n //skipping duplicate columns based on the already sorted row\n if (col > 0 && mat[row][col] == mat[row][col - 1]) {\n continue; \n }\n }\n \n return memo[row][remain] = min;\n }\n}\n```
2
0
[]
1
minimize-the-difference-between-target-and-chosen-elements
[Python3] 2 solutions - dp & bitset
python3-2-solutions-dp-bitset-by-ye15-h375
Please check this commit for solutions of weekly 255. \n\nApproach 1 -- dp (9228ms, 8.91%)\n\nclass Solution:\n def minimizeTheDifference(self, mat: List[Lis
ye15
NORMAL
2021-08-24T20:07:24.008487+00:00
2021-08-24T21:52:48.745645+00:00
316
false
Please check this [commit](https://github.com/gaosanyong/leetcode/commit/12942515a0e681f7ed804e66ec8de2b3423cadb0) for solutions of weekly 255. \n\n**Approach 1 -- dp** (9228ms, 8.91%)\n```\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n m, n = len(mat), len(mat[0])\n mn = [min(row) for row in mat]\n \n @cache \n def fn(i, x): \n """Return minimum absolute difference."""\n if i == m: return abs(x)\n if x <= 0: return fn(i+1, x-mn[i])\n ans = inf \n for j in range(n): \n ans = min(ans, fn(i+1, x-mat[i][j]))\n return ans \n \n return fn(0, target)\n```\n\n**Approach 2 - bitset** (188ms, 99.86%)\n```\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n mask = 0b1\n for row in mat: \n temp = 0\n for x in row: temp |= mask << x\n mask = temp \n \n for x in range(5000): \n if mask >> (target+x) & 1 or x <= target and mask >> (target-x) & 1: return x\n```
2
1
['Python3']
2
minimize-the-difference-between-target-and-chosen-elements
100% Efficient | Simple Recursion + Memoization
100-efficient-simple-recursion-memoizati-iycc
\n\nclass Solution {\npublic:\n int recc(vector<vector<int>>& mat, int sum,int n,vector<vector<int>>&m){\n if(n==0){\n return abs(sum);\n
dsslayer
NORMAL
2021-08-23T13:10:39.479128+00:00
2021-08-23T13:17:53.267629+00:00
426
false
```\n\nclass Solution {\npublic:\n int recc(vector<vector<int>>& mat, int sum,int n,vector<vector<int>>&m){\n if(n==0){\n return abs(sum);\n }\n if(sum<=0){\n return INT_MAX;\n }\n if(m[n][sum]!=-1){\n return m[n][sum];\n }\n int ans=INT_MAX;\n for(int i=0;i<mat[n-1].size();i++){\n ans=min(ans,recc(mat,sum-mat[n-1][i],n-1,m));\n }\n return m[n][sum]=ans;\n }\n int minimizeTheDifference(vector<vector<int>>& mat, int t) {\n int maxs=0,mins=0;\n for(int i=0;i<mat.size();i++){\n int mx=INT_MIN,mn=INT_MAX;\n for(int j=0;j<mat[0].size();j++){\n mx=max(mx,mat[i][j]);\n mn=min(mn,mat[i][j]);\n }\n maxs+=mx;\n mins+=mn;\n }\n if(t<=mins){\n return mins-t;\n }\n if(t>=maxs){\n return t-maxs;\n }\n vector<vector<int>>m(mat.size()+1,vector<int>(t+1,-1));\n return recc(mat,t,mat.size(),m);\n }\n};\n\n```
2
0
['Recursion', 'Memoization', 'C']
1
minimize-the-difference-between-target-and-chosen-elements
C++ 0-1 Knapsack Implementation
c-0-1-knapsack-implementation-by-galexw-hgl4
```\nclass Solution {\npublic:\n int minimizeTheDifference(vector>& mat, int target) {\n int m = mat.size();\n\n int MAX_SUM = 70 * 70;\n vect
galexw
NORMAL
2021-08-22T21:59:36.993663+00:00
2021-08-22T21:59:50.315386+00:00
218
false
```\nclass Solution {\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n int m = mat.size();\n\n int MAX_SUM = 70 * 70;\n vector<vector<bool>> dp(m, vector<bool>(MAX_SUM + 1));\n\n for (auto num : mat[0]) {\n dp[0][num] = true;\n }\n\n for (int i = 0; i < m - 1; i++) {\n vector<int>& nextRow = mat[i + 1];\n unordered_set<int> s (nextRow.begin(), nextRow.end());\n for (int w = 0; w <= MAX_SUM; w++) {\n if (dp[i][w]) {\n for (auto num : s) {\n if (w + num <= MAX_SUM) {\n dp[i + 1][w + num] = dp[i][w];\n }\n } \n }\n }\n }\n\n int bestDiff = 1e9 + 7;\n\n for (int w = 0; w <= MAX_SUM; w++) {\n bool possible = dp[m - 1][w];\n if (possible) {\n int diff = abs(target - w);\n if (diff < bestDiff) {\n bestDiff = diff;\n }\n }\n }\n return bestDiff;\n }\n};
2
0
[]
0
minimize-the-difference-between-target-and-chosen-elements
[C++] Simple O(m * n * target) DP solution
c-simple-om-n-target-dp-solution-by-code-2bop
Here is yet another tribute to my idol @lee215\n\nIntuition:\n1. Think of it similar to 0-1 knapsack problem. Here, the difference is that you have to choose on
coderplustester
NORMAL
2021-08-22T11:22:48.737474+00:00
2021-08-22T11:22:48.737507+00:00
148
false
Here is yet another tribute to my idol @lee215\n\nIntuition:\n1. Think of it similar to 0-1 knapsack problem. Here, the difference is that you have to choose one column in every row in this case and you have to choose an element.\n \n```\nclass Solution {\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n vector<int> dp(target + 1);\n int m = mat.size(), n = mat[0].size();\n \n\t\t// base case: If number of rows is zero, target is your min abs diff.\n for (int i = 0; i <= target; i++) {\n dp[i] = i;\n }\n \n for (int k = 0; k < m; k++) {\n for (int i = target; i > 0; i--) {\n dp[i] = numeric_limits<int>::max();\n for (int j = 0; j < n; j++) {\n\t\t\t\t\t// for every column, if value <= i, min abs diff after choosing value will\n\t\t\t\t\t// be min(min abs diff of last row with target (i - value), min abs diff found\n\t\t\t\t\t// till now), otherwise it will be (value - i) + min abs diff of last row with target 0. \n\t\t\t\t\t// This is done to ensure that the abs diff is minimum. \n dp[i] = min(dp[i], mat[k][j] <= i ? dp[i - mat[k][j]] : (mat[k][j] - i + dp[0]));\n }\n }\n\t\t\t// This is handled separately to handle integer overflow for (mat[k][j] - i + dp[0])\n dp[0] = dp[1] + 1;\n }\n \n return dp[target];\n }\n};\n```\n\n**Time and Space Complexity:**\nSimilar to 0-1 knapsack problem (which can be solved in O(n * k) time, O(k) space complexity), This can be solved in **O(m * n * target)** time, **O(k)** space.
2
0
[]
1
minimize-the-difference-between-target-and-chosen-elements
Easy Well Commented: Memoization
easy-well-commented-memoization-by-raj_s-exbg
\nclass Solution {\npublic:\n int dp[5001][71];\n int mini = INT_MAX;\n int find(vector<vector<int>>& mat,int i,int sum,int tar)\n {\n\t\tif(dp[sum]
raj_srivastava
NORMAL
2021-08-22T09:09:48.591593+00:00
2022-02-06T08:33:31.489962+00:00
186
false
```\nclass Solution {\npublic:\n int dp[5001][71];\n int mini = INT_MAX;\n int find(vector<vector<int>>& mat,int i,int sum,int tar)\n {\n\t\tif(dp[sum][i]!=-1) return dp[sum][i];\n\t\t//Base Case\n\t\t//When we consume all the rows , update the min answer till now.\n if(i>=mat.size()){\n mini = min(mini,abs(sum-tar));\n return dp[sum][i] = abs(sum-tar);\n }\n\t\t//For early exit:\n\t\t//if sum has already exceeded target, then going forward, this difference \n\t\t//is always going to increase only ,as all elements are positive and if the current \n\t\t//difference is already greater than mini, then this can\'t be our potential answer:\n\t\t//So, stop right there:\n if(tar<sum && abs(sum-tar)>mini){\n return dp[sum][i] = 5000;\n }\n \n\t\t//Trying out all the combination selecting one element from each row\n int ans=INT_MAX;\n for(int j=0;j<mat[i].size();j++)\n {\n\t\t//since every row is sorted , so if we encounter the same element on a row again , \n\t\t// it will ultimately give the same result as previous one, so it won\'t be of any use\n\t\t//to us, so we skip it\n if(j!=0 && mat[i][j]==mat[i][j-1]) continue;\n ans=min(ans,find(mat,i+1,sum+mat[i][j],tar));\n }\n return dp[sum][i]=ans;\n }\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n memset(dp,-1,sizeof(dp));\n\t\t//Make the matrix rowwise sorted\n for(int i=0;i<mat.size();i++){\n sort(mat[i].begin(),mat[i].end());\n }\n return find(mat,0,0,target);\n \n }\n};\n```
2
0
['Dynamic Programming', 'C', 'Sorting']
0
minimize-the-difference-between-target-and-chosen-elements
C#
c-by-ve7545-zpri
Runtime: 1417 ms\nMemory Usage: 29.8 MB\n\npublic class Solution {\n public int MinimizeTheDifference(int[][] mat, int target) {\n HashSet<int> crnt =
ve7545
NORMAL
2021-08-22T04:42:31.124962+00:00
2021-08-22T04:42:31.124988+00:00
94
false
Runtime: 1417 ms\nMemory Usage: 29.8 MB\n```\npublic class Solution {\n public int MinimizeTheDifference(int[][] mat, int target) {\n HashSet<int> crnt = new HashSet<int>();\n HashSet<int> prev = new HashSet<int>();\n HashSet<int> temp;\n \n int next = int.MaxValue;\n \n for(int i=0; i< mat[0].Length; i++)\n {\n if (mat[0][i] >= target) \n { \n next = Math.Min(next, mat[0][i]); // keep smallest bigger number\n }\n else\n {\n crnt.Add(mat[0][i]); // add all smaller\n }\n }\n \n int prevNext = next;\n for(int i=1; i < mat.Length; i++)\n {\n prevNext = next; \n next = int.MaxValue;\n \n temp = prev;\n prev = crnt;\n crnt = temp;\n crnt.Clear();\n \n for(int j=0; j < mat[i].Length; j++)\n {\n if (prevNext + mat[i][j] >= target)\n {\n next = Math.Min(next, prevNext + mat[i][j]);\n }\n foreach(int val in prev)\n {\n if (val + mat[i][j] >= target)\n {\n next = Math.Min(next, val + mat[i][j]); \n }\n else\n {\n crnt.Add(val + mat[i][j]);\n }\n }\n }\n }\n \n int result = next - target;\n \n foreach(int val in crnt)\n {\n if (Math.Abs(val - target) < result) { result = Math.Abs(val - target); }\n }\n \n return result;\n }\n}\n```
2
1
[]
0
minimize-the-difference-between-target-and-chosen-elements
JAVA || EASY || SOLUTION
java-easy-solution-by-ritwikrst-3m5m
\n private int min; \n private int[][] visited; \n public void solve(int[][] a, int sum, int row, int target){\n if(row>=a.length){\n m
ritwikrst
NORMAL
2021-08-22T04:34:15.742287+00:00
2021-08-22T04:34:15.742378+00:00
349
false
```\n private int min; \n private int[][] visited; \n public void solve(int[][] a, int sum, int row, int target){\n if(row>=a.length){\n min=Math.min(min, Math.abs(target-sum));\n return;\n } \n if(visited[row][sum] == 1) \n return;\n for(int j=0; j<a[0].length; j++){\n solve(a, sum+a[row][j], row+1, target);\n\n }\n visited[row][sum] = 1; \n }\n\n public int minimizeTheDifference(int[][] mat, int target) {\n min = Integer.MAX_VALUE;\n visited = new int[mat.length][10000];\n solve(mat, 0, 0, target);\n return min;\n }\n```
2
1
['Java']
1
minimize-the-difference-between-target-and-chosen-elements
dp 70*70*800
dp-7070800-by-kira3018-g17a
\nclass Solution {\npublic:\n int prefix[80] = {0};\n int minimizeTheDifference(vector<vector<int>>& mat, int target) \n {\n vector<vector<int>>
kira3018
NORMAL
2021-08-22T04:23:41.808788+00:00
2021-08-22T04:23:41.808824+00:00
141
false
```\nclass Solution {\npublic:\n int prefix[80] = {0};\n int minimizeTheDifference(vector<vector<int>>& mat, int target) \n {\n vector<vector<int>> vec(mat.size(),vector<int>(800,INT_MAX));\n for(int i = mat.size()-1;i >= 0;i--)\n {\n int a = INT_MAX;\n for(int j = 0;j < mat[0].size();j++)\n a = min(a,mat[i][j]);\n prefix[i] = prefix[i+1]+a;\n }\n return abs(solve(mat,target,0,0,vec));\n }\n int solve(vector<vector<int>>& mat,int target,int index,int sum,vector<vector<int>>& vec)\n {\n int diff = INT_MAX;\n if(index == mat.size())\n return target-sum;\n if(sum >= target)\n return target-sum-prefix[index];\n if(vec[index][sum]!=INT_MAX)\n return vec[index][sum];\n for(int j = 0;j < mat[0].size();j++){\n int a = solve(mat,target,index+1,sum+mat[index][j],vec);\n if(abs(diff) > abs(a))\n diff = a;\n }\n return vec[index][sum] = diff;\n }\n};\n```
2
0
[]
0
minimize-the-difference-between-target-and-chosen-elements
C++ Straightforward Hash Set Solution
c-straightforward-hash-set-solution-by-z-2m5i
All possible sums are in the range [1, 4900], so we can pre-calculate them.\nAn optimization is for all sums > 800, only keep the smallest.\nC++\nclass Solution
ztyreg
NORMAL
2021-08-22T04:08:21.872966+00:00
2021-08-22T04:37:22.427175+00:00
162
false
All possible sums are in the range [1, 4900], so we can pre-calculate them.\nAn optimization is for all sums > 800, only keep the smallest.\n```C++\nclass Solution {\npublic:\n \n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n int m = mat.size();\n int n = mat[0].size();\n unordered_set<int> s = {};\n s.insert(0);\n for (int i = 0; i < m; i++) {\n unordered_set<int> small = {};\n int large = INT_MAX;\n for (auto a: s) {\n for (auto b : mat[i]) {\n int v = a + b;\n if (v <= target) {\n small.insert(v);\n } else {\n large = min(large, v);\n }\n }\n }\n s = small;\n if (large != INT_MAX) {\n s.insert(large);\n }\n }\n \n int res = INT_MAX;\n for (auto a : s) {\n res = min(res, abs(target - a));\n }\n \n return res;\n \n }\n \n};\n\n```
2
0
['Ordered Set', 'C++']
0
minimize-the-difference-between-target-and-chosen-elements
[python3] simple dfs solution with optimizations
python3-simple-dfs-solution-with-optimiz-sjly
\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n ## RC ##\n ## APPROACH: DFS ##\n result
101leetcode
NORMAL
2021-08-22T04:04:12.059477+00:00
2021-08-22T04:51:01.615511+00:00
613
false
```\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n ## RC ##\n ## APPROACH: DFS ##\n result = float(\'inf\')\n cache = set()\n def dfs(row, res):\n nonlocal result\n \n if (row, res) in cache:\n return\n\n # optimization\n if result == 0:\n return\n \n if row == len(mat):\n result = min(result, abs(target - res))\n return\n \n for i in range(0, len(mat[row])):\n dfs(row + 1, res + mat[row][i])\n \n\t\t\t# optimation\n cache.add((row, res))\n \n for i in range(0, len(mat)):\n # optimation\n mat[i] = list(set(mat[i]))\n \n dfs(0, 0)\n return result\n```
2
0
['Depth-First Search']
4
minimize-the-difference-between-target-and-chosen-elements
Simple Java Solution | memoization
simple-java-solution-memoization-by-hxgx-thik
Well its simple backtracking with memoization. Comments in the code are self explanatory!\n\nclass Solution {\n\n int abs; //global variabls to keep minimum
hxgxs1
NORMAL
2021-08-22T04:01:18.437912+00:00
2021-08-22T04:08:55.881964+00:00
516
false
Well its simple backtracking with memoization. Comments in the code are self explanatory!\n\nclass Solution {\n\n int abs; //global variabls to keep minimum abs value\n int[][] dp; // whenever we arrive at a particular row we need to see if we had previously arrived on this row with same sum.\n public void recFunc(int[][] a, int sum, int row, int target){\n if(row>=a.length){\n abs=Math.min(abs, Math.abs(target-sum));\n return;\n } \n if(dp[row][sum]==1) // we have arrived this row before with the same sum value, and calculated resultant abs min value. \n return;\n for(int j=0;j<a[0].length;j++){\n recFunc(a, sum+a[row][j], row+1, target);\n \n }\n dp[row][sum]=1; // mark that we arrives at "row" with "sum", and have calucated resultant min abs value. \n }\n \n public int minimizeTheDifference(int[][] mat, int target) {\n abs=Integer.MAX_VALUE;\n dp=new int[mat.length][50000];\n recFunc(mat, 0, 0, target);\n return abs;\n }\n}\n\nCheers!
2
0
['Dynamic Programming', 'Backtracking']
2
minimize-the-difference-between-target-and-chosen-elements
Tabulation code easy C++
tabulation-code-easy-c-by-sumitdarshanal-h2qs
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
sumitdarshanala
NORMAL
2024-06-11T17:11:53.933598+00:00
2024-06-11T17:11:53.933627+00:00
56
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n*m*(70*70)) ~= cosidered 5000 approx\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(n*(70*70))\n# Code\n```\nclass Solution {\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n int n = mat.size();\n int maxSum = 5000; // maximum possible sum given the constraints\n\n // Initialize a DP table with false values\n vector<vector<bool>> dp(n + 1, vector<bool>(maxSum + 1, false));\n dp[0][0] = true; // base case: sum of 0 with 0 rows considered\n\n // Fill the DP table\n for (int i = 1; i <= n; ++i) {\n for (int j = 0; j <= maxSum; ++j) {\n if (dp[i - 1][j]) {\n for (int k : mat[i - 1]) {\n if (j + k <= maxSum) {\n dp[i][j + k] = true;\n }\n }\n }\n }\n }\n\n // Find the minimum absolute difference\n int result = INT_MAX;\n for (int j = 0; j <= maxSum; ++j) {\n if (dp[n][j]) {\n result = min(result, abs(j - target));\n }\n }\n\n return result;\n }\n};\n\n```
1
0
['Dynamic Programming', 'Memoization', 'C++']
0
minimize-the-difference-between-target-and-chosen-elements
Easy Python Solution
easy-python-solution-by-synch-ab0u
Thought process\n\nQ: What is the brute force method? \n\n-> recursion over each row, try every element in each row within the recursive function, which tracks
synch
NORMAL
2024-05-15T20:43:36.876833+00:00
2024-05-15T20:43:36.876886+00:00
213
false
# Thought process\n\nQ: What is the brute force method? \n\n-> recursion over each row, try every element in each row within the recursive function, which tracks `(idx, current_sum)`.\n\nQ: What is the bottleneck?\n-> For loops. How do we reduce the search space?\n-> 1. Naive idea: remove duplicate in the row. => iterate over `set(row)`.\n-> 2. keep solving the same problem for the same `(idx, sum)`: Memoization.\n\nBut I was still getting TLE. What can be done further?\n\n-> I reallized that the minimum absolute difference is 0. If the result hits 0, I should return right away.\n\n-> With these, the solution gets accepted, beating 52%. Not the most optimal solution, but the easiest solution to me.\n\n# Complexity\n- Time complexity: $O(n^2)$ if all intermediate sums are unique making memoization useless.\n\n- Space complexity: $O(n^2)$ for memoing.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n @cache\n def solve(idx, curr_sum):\n if idx == len(mat):\n return abs(target - curr_sum)\n \n min_res = float("inf")\n for x in set(mat[idx]):\n res = solve(idx + 1, curr_sum + x)\n min_res = min(res, min_res)\n if min_res == 0:\n return 0\n return min_res\n\n return solve(0, 0)\n\n```
1
0
['Python3']
0
minimize-the-difference-between-target-and-chosen-elements
Beats 50%, brute force, O(m*n^m)
beats-50-brute-force-omnm-by-igor0-hjnw
Intuition\nJust create a set for with all possible sums for each row.\n\n# Approach\nAt first create a set with all possible sums for the last row:\n\nvar set =
igor0
NORMAL
2024-02-21T20:23:48.990085+00:00
2024-02-21T20:23:48.990150+00:00
11
false
# Intuition\nJust create a set for with all possible sums for each row.\n\n# Approach\nAt first create a set with all possible sums for the last row:\n```\nvar set = new HashSet<int>(mat[mat.Length - 1]);\n```\nThen go through the all rows and create a set with all possible sums by each iteration:\n```\nfor (int i = mat.Length - 2; i >= 0; i--)\n{\n var set2 = new HashSet<int>();\n foreach(var item in set)\n {\n for (int j = 0; j < mat[i].Length; j++)\n {\n set2.Add(item + mat[i][j]);\n }\n }\n set = set2;\n}\n```\nFinally calculate the result:\n```\nvar rs = int.MaxValue;\nforeach(var item in set)\n{\n rs = Math.Min(rs, Math.Abs(item - target));\n}\nreturn rs;\n```\n\n# Complexity\n- Time complexity:\n$$O(m*n^m)$$, where n is the len(mat[0]) and m is len(mat)\n\n- Space complexity:\n$$O(n^m)$$, where n is the len(mat[0]) and m is len(mat)\n\n# Code\n```\npublic class Solution {\n public int MinimizeTheDifference(int[][] mat, int target) {\n var set = new HashSet<int>(mat[mat.Length - 1]);\n for (int i = mat.Length - 2; i >= 0; i--)\n {\n var set2 = new HashSet<int>();\n foreach(var item in set)\n {\n for (int j = 0; j < mat[i].Length; j++)\n {\n set2.Add(item + mat[i][j]);\n }\n }\n set = set2;\n }\n var rs = int.MaxValue;\n foreach(var item in set)\n {\n rs = Math.Min(rs, Math.Abs(item - target));\n }\n return rs;\n }\n}\n```
1
0
['C#']
0
minimize-the-difference-between-target-and-chosen-elements
DP(Recursive) + Memoization optimize Solution
dprecursive-memoization-optimize-solutio-n72u
Complexity\n- Time complexity:O(nm)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(nm)\n Add your space complexity here, e.g. O(n) \n\n# Co
Shree_Govind_Jee
NORMAL
2023-12-29T02:15:57.800397+00:00
2023-12-29T02:15:57.800414+00:00
56
false
# Complexity\n- Time complexity:$$O(n*m)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n*m)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n// Recursive Solution\n private int solveRec(int[][] mat, int target, int idx, int val){\n //Base Case\n if(idx == mat.length){\n return Math.abs(val-target);\n }\n\n int min = Integer.MAX_VALUE;\n for(int i=0; i<mat[0].length; i++){\n min = Math.min(min,solveRec(mat, target, idx+1, val+mat[idx][i]));\n }\n return min;\n }\n\n\n\n// DP + Memoization SOlution\n private int solveMemo(int[][] mat, int target, int[][] dp, int idx, int val){\n //Base Case\n if(idx == mat.length){\n return Math.abs(val-target);\n }\n\n //step-3 => if dp[idx][val] is already calculated the just return it\n if(dp[idx][val] != -1){\n return dp[idx][val];\n }\n\n //step-2 =>if dp[idx][val] isn\'t calculated then just calculate it and put it in the dp\n int min = Integer.MAX_VALUE;\n for(int i=0; i<mat[0].length; i++){\n min = Math.min(min, solveMemo(mat, target, dp, idx+1, val+mat[idx][i]));\n }\n return dp[idx][val] = min;\n }\n\n\n\n\n// Drive Function\n public int minimizeTheDifference(int[][] mat, int target) {\n // return solveRec(mat, target, 0, 0);\n\n\n int[][] dp = new int[mat.length][5001];\n for(int i=0; i<dp.length; i++){\n Arrays.fill(dp[i], -1);\n }\n\n return solveMemo(mat, target, dp, 0, 0);\n }\n}\n```
1
0
['Array', 'Dynamic Programming', 'Recursion', 'Memoization', 'Matrix', 'Java']
0
minimize-the-difference-between-target-and-chosen-elements
[Kotlin] DP | Fastest
kotlin-dp-fastest-by-user1572h-wt99
```\nclass Solution {\n private val minDiff = mutableMapOf()\n \n fun minimizeTheDifference(mat: Array, target: Int): Int {\n return getMinDiff(
user1572h
NORMAL
2022-09-10T13:53:39.458458+00:00
2022-09-10T13:54:07.331322+00:00
24
false
```\nclass Solution {\n private val minDiff = mutableMapOf<Int, Int>()\n \n fun minimizeTheDifference(mat: Array<IntArray>, target: Int): Int {\n return getMinDiff(mat, 0, target)\n }\n \n fun getMinDiff(mat: Array<IntArray>, firstRow: Int, target: Int): Int {\n var cached = minDiff[firstRow * 1000 + target]\n if (cached == null) {\n var min = Int.MAX_VALUE\n for(value in mat[firstRow]) {\n val diff = if (firstRow >= mat.size - 1) {\n Math.abs(target - value)\n } else if (target - value < 0) {\n getMinDiff(mat, firstRow + 1, 0) - (target - value)\n } else {\n getMinDiff(mat, firstRow + 1, target - value)\n }\n\n min = Math.min(min, diff)\n }\n cached = min\n minDiff[firstRow * 1000 + target] = min\n }\n \n return cached\n }\n}
1
0
['Kotlin']
0
minimize-the-difference-between-target-and-chosen-elements
Cleanest || Intuitative Approach
cleanest-intuitative-approach-by-priyans-pu2u
\n int solve(int i, vector<vector<int>>& m, int target, int sum, vector<vector<int>> &dp)\n {\n if(i == m.size())\n return abs(sum-targe
priyanshuHere27
NORMAL
2022-09-02T04:05:35.953738+00:00
2022-09-02T04:05:35.953781+00:00
437
false
```\n int solve(int i, vector<vector<int>>& m, int target, int sum, vector<vector<int>> &dp)\n {\n if(i == m.size())\n return abs(sum-target);\n \n if(dp[i][sum]!=-1)\n return dp[i][sum];\n \n int ans = INT_MAX;\n for(int j=0;j<m[0].size();j++)\n {\n ans = min(ans, solve(i+1, m, target, sum+m[i][j], dp));\n if(ans == 0)\n return 0;\n }\n return dp[i][sum] = ans;\n }\n int minimizeTheDifference(vector<vector<int>>& m, int target) {\n int sum = 0;\n for(int i=0;i<m.size();i++)\n {\n int mx = INT_MIN;\n for(int j=0;j<m[0].size();j++)\n mx = max(mx, m[i][j]);\n sum += mx;\n }\n vector<vector<int>> dp(m.size(), vector<int>(sum+1, -1));\n return solve(0, m, target, 0, dp);\n }\n```
1
0
['Dynamic Programming', 'Memoization', 'C', 'C++']
1
minimize-the-difference-between-target-and-chosen-elements
JAVA|Recursive |dp
javarecursive-dp-by-deysouvik955-4491
\n\n\tint ans=Integer.MAX_VALUE;\n Integer[][] dp=null;\n public int minimizeTheDifference(int[][] mat, int target) {\n dp=new Integer[mat.length][
deysouvik955
NORMAL
2022-08-09T16:01:03.214436+00:00
2022-08-09T16:01:03.214474+00:00
512
false
```\n\n\tint ans=Integer.MAX_VALUE;\n Integer[][] dp=null;\n public int minimizeTheDifference(int[][] mat, int target) {\n dp=new Integer[mat.length][71*71];\n ans=Integer.MAX_VALUE;\n dfs(0,mat,target,0);\n return ans;\n }\n void dfs(int row,int mat[][],int t,int sum){\n if(row==mat.length){\n ans=Math.min(Math.abs(t-sum),ans);\n return;\n }\n if(dp[row][sum]!=null) return;\n for(int i=0;i<mat[0].length;i++){\n dfs(row+1,mat,t,sum+mat[row][i]);\n }\n dp[row][sum]=1;\n }\n```
1
0
['Dynamic Programming', 'Memoization', 'Java']
1
minimize-the-difference-between-target-and-chosen-elements
85% TC and 84% SC easy python solution
85-tc-and-84-sc-easy-python-solution-by-jo2yj
\ndef minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n\tm = len(mat)\n\tfor i in range(m):\n\t\tmat[i].sort()\n\tq = set([0])\n\tfor i i
nitanshritulon
NORMAL
2022-07-28T11:09:43.599710+00:00
2022-07-28T11:10:48.459809+00:00
431
false
```\ndef minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n\tm = len(mat)\n\tfor i in range(m):\n\t\tmat[i].sort()\n\tq = set([0])\n\tfor i in range(m):\n\t\ttemp = set()\n\t\tfor num1 in q:\n\t\t\tfor num2 in mat[i]:\n\t\t\t\ttemp.add(num1+num2)\n\t\t\t\tif(num1+num2 > target):\n\t\t\t\t\tbreak\n\t\tq = temp\n\tq = sorted(list(q))\n\ti = bisect_right(q, target)\n\tif(i == len(q)):\n\t\treturn target - q[-1]\n\tif(i == 0):\n\t\treturn q[0] - target\n\treturn min(target-q[i-1], q[i]-target)\n```
1
0
['Binary Tree', 'Python', 'Python3']
0
minimize-the-difference-between-target-and-chosen-elements
JAVA : RECURSIVE(TLE)+MEMOIZATION(ACCEPTED),EASY
java-recursivetlememoizationacceptedeasy-wjsr
RECURSIVE(TLE)\n\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n int min=Integer.MAX_VALUE; \n int n=mat.length;
l_e_s_s_o_r_d_i_nary
NORMAL
2022-07-15T13:04:27.310549+00:00
2022-07-15T13:04:27.310577+00:00
343
false
**RECURSIVE(TLE)**\n```\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n int min=Integer.MAX_VALUE; \n int n=mat.length;\n int m=mat[0].length;\n \n for(int i=0;i<m;i++){\n min=Math.min(min,solve(mat,0,0,i,n,m,target));\n // System.out.println(solve(mat,0,0,i,n,m,target));\n } \n return min; \n }\n public int solve(int mat[][],int sum,int i,int j,int n,int m,int target){\n if(i==n)\n return Math.abs(sum-target);\n int ans=Integer.MAX_VALUE;\n for(int k=0;k<m;k++)\n {\n ans=Math.min(ans,solve(mat,sum+mat[i][k],i+1,k,n,m,target));\n }\n return ans; \n }\n}\n```\n\n**MEMOIZATION(ACCEPTED)**\n```\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n int min=Integer.MAX_VALUE; \n int n=mat.length;\n int m=mat[0].length;\n int dp[][]=new int[71][71*71];\n for(int i[]:dp)\n Arrays.fill(i,-1);\n for(int i=0;i<m;i++){\n min=Math.min(min,solve(mat,0,0,i,n,m,target,dp));\n // System.out.println(solve(mat,0,0,i,n,m,target));\n } \n return min; \n }\n public int solve(int mat[][],int sum,int i,int j,int n,int m,int target,int dp[][]){\n if(i==n)\n return Math.abs(sum-target);\n if(dp[i][sum]!=-1)\n return dp[i][sum];\n int ans=Integer.MAX_VALUE;\n for(int k=0;k<m;k++)\n {\n ans=Math.min(ans,solve(mat,sum+mat[i][k],i+1,k,n,m,target,dp));\n }\n return dp[i][sum]=ans; \n }\n}\n```
1
0
['Recursion', 'Memoization', 'Java']
0
minimize-the-difference-between-target-and-chosen-elements
Fully optimized DP Top Down Approach
fully-optimized-dp-top-down-approach-by-kzc5a
\nclass Solution {\npublic:\n \n int ans=INT_MAX;\n int helper(int i,int sum,int &n,vector<vector<int>>&dp,vector<vector<int>>&mat,int &target)\n {\n
dhruvjain04
NORMAL
2022-06-16T03:44:22.297888+00:00
2022-06-16T03:45:22.304583+00:00
281
false
```\nclass Solution {\npublic:\n \n int ans=INT_MAX;\n int helper(int i,int sum,int &n,vector<vector<int>>&dp,vector<vector<int>>&mat,int &target)\n {\n if(i==n)\n {\n ans=min(ans,abs(target-sum));\n return abs(target-sum);\n }\n if(dp[i][sum]!=-1)return dp[i][sum];\n \n if(sum-target>ans)return INT_MAX;\n \n int min_diff=INT_MAX;\n \n for(int j=0;j<mat[0].size();j++)\n {\n min_diff=min(min_diff,helper(i+1,sum+mat[i][j],n,dp,mat,target));\n if(min_diff==0)return dp[i][sum]=min_diff;\n }\n return dp[i][sum]=min_diff;\n }\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n \n int n=mat.size();\n vector<vector<int>>dp(n,vector<int>(5000,-1));\n return helper(0,0,n,dp,mat,target);\n \n \n }\n};\n```
1
0
['Dynamic Programming', 'C']
0
minimize-the-difference-between-target-and-chosen-elements
Scala
scala-by-fairgrieve-5puw
\nimport scala.util.chaining.scalaUtilChainingOps\n\nobject Solution {\n def minimizeTheDifference(mat: Array[Array[Int]], target: Int): Int = mat\n .foldLe
fairgrieve
NORMAL
2022-05-03T01:55:37.468779+00:00
2022-05-03T01:55:37.468821+00:00
49
false
```\nimport scala.util.chaining.scalaUtilChainingOps\n\nobject Solution {\n def minimizeTheDifference(mat: Array[Array[Int]], target: Int): Int = mat\n .foldLeft(Set(0), Option.empty[Int]) {\n case lessThanTarget -> noLessThanTarget -> row => lessThanTarget\n .iterator\n .concat(noLessThanTarget)\n .flatMap(sum => row.iterator.map(sum + _))\n .partition(_ < target)\n .pipe { case lessThanTarget -> noLessThanTarget => lessThanTarget.toSet -> noLessThanTarget.minOption }\n }\n .pipe {\n case lessThanTarget -> noLessThanTarget => lessThanTarget\n .iterator\n .concat(noLessThanTarget)\n .map(_ - target)\n .map(math.abs)\n .min\n }\n}\n```
1
0
['Scala']
0
minimize-the-difference-between-target-and-chosen-elements
JavaScript Solution - Top Down DP Approach
javascript-solution-top-down-dp-approach-rhei
\nvar minimizeTheDifference = function(mat, target) {\n const MAX = Number.MAX_SAFE_INTEGER;\n \n const m = mat.length;\n const n = mat[0].length;\n
Deadication
NORMAL
2022-04-25T15:57:03.684189+00:00
2022-04-25T15:57:03.684233+00:00
218
false
```\nvar minimizeTheDifference = function(mat, target) {\n const MAX = Number.MAX_SAFE_INTEGER;\n \n const m = mat.length;\n const n = mat[0].length;\n \n const memo = [];\n \n for (let i = 0; i < m; ++i) {\n memo[i] = new Array(4901).fill(MAX);\n }\n \n return topDown(0, 0);\n \n function topDown(row, sum) {\n if (row === m) return Math.abs(target - sum);\n if (memo[row][sum] != MAX) return memo[row][sum];\n \n let min = MAX;\n \n mat[row].sort((a, b) => a - b); \n \n const set = new Set(mat[row]);\n \n for (const num of set) {\n const res = topDown(row + 1, sum + num);\n \n if (res > min) break;\n min = res;\n }\n \n memo[row][sum] = min;\n \n return min;\n }\n};\n```
1
0
['Dynamic Programming', 'JavaScript']
1
minimize-the-difference-between-target-and-chosen-elements
Java || DP || Easy to Understand
java-dp-easy-to-understand-by-itsmohitmk-mkka
```\nclass Solution {\n int[][] dp;\n public int minimizeTheDifference(int[][] mat, int target) {\n int n = mat.length , m = mat[0].length;\n
itsmohitmk99
NORMAL
2022-04-21T11:52:44.178537+00:00
2022-04-21T11:52:44.178568+00:00
376
false
```\nclass Solution {\n int[][] dp;\n public int minimizeTheDifference(int[][] mat, int target) {\n int n = mat.length , m = mat[0].length;\n \n dp = new int[n][5000];\n for(int i = 0 ; i< n ; i++){\n for(int j = 0 ; j < 5000 ; j++){\n dp[i][j] = Integer.MAX_VALUE;\n }\n }\n return solve(mat , 0 , 0 , target , n , m);\n }\n \n int solve(int[][] arr , int i , int curr , int target , int n , int m){\n if(i == n){\n return Math.abs(target - curr);\n }\n \n if(dp[i][curr] != Integer.MAX_VALUE) return dp[i][curr];\n \n int min = Integer.MAX_VALUE;\n \n for(int k = 0 ; k < m ; k++){\n min = Math.min(min , solve(arr , i+1 ,curr + arr[i][k] , target , n , m)); \n }\n \n return dp[i][curr] = min;\n \n }\n \n}
1
0
['Dynamic Programming', 'Java']
0
minimize-the-difference-between-target-and-chosen-elements
dp,memoization
dpmemoization-by-amreshhere-5j6d
class Solution {\npublic:\n int dp[71][5000];\n void funct(vector>& mat,int n,int m,int target,int &ans,int k,int sum)\n {\n if(dp[k][sum]!=-
amreshhere
NORMAL
2022-03-29T08:48:59.561260+00:00
2022-03-29T08:48:59.561284+00:00
173
false
class Solution {\npublic:\n int dp[71][5000];\n void funct(vector<vector<int>>& mat,int n,int m,int target,int &ans,int k,int sum)\n {\n if(dp[k][sum]!=-1)\n return;\n dp[k][sum]=1; \n if(k==n)\n {\n ans=min(ans,abs(target-sum));\n return;\n }\n for(int i=0;i<m;i++)\n {\n funct(mat,n,m,target,ans,k+1,sum+mat[k][i]); \n }\n }\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n int n=mat.size();\n int m=mat[0].size();\n memset(dp,-1,sizeof(dp));\n int ans=INT_MAX;\n funct(mat,n,m,target,ans,0,0); \n return ans;\n }\n};\n\n
1
1
['Dynamic Programming', 'Recursion', 'Memoization']
0
minimize-the-difference-between-target-and-chosen-elements
Python (Faster than 93.96%) Little Explanation
python-faster-than-9396-little-explanati-96ck
\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n\t\t# initialise set of attainable numbers using the first ro
jinyang_deng
NORMAL
2022-03-27T01:26:36.597818+00:00
2022-03-27T01:26:54.819532+00:00
175
false
```\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n\t\t# initialise set of attainable numbers using the first row\n arr = set(mat[0])\n \n\t\t# from the second row onwards\n\t\t# we add every number in arr with every number in the row\n for row in mat[1:]:\n arr1 = set()\n for num1 in row:\n for num2 in arr:\n arr1.add(num1 + num2)\n \n\t\t\t# if there are 1 or more number bigger than target, we only need to keep the smallest one\n\t\t\t# because the larger numbers are considered further from target, and will only get even further as we move towards the bottom\n minMax = float(\'inf\')\n for num in arr1:\n if num > target:\n minMax = min(minMax, num)\n arr = set()\n for num in arr1:\n if num <= minMax:\n arr.add(num)\n\t\t\n\t\t# find the smallest distance between each number in the attainable array and the target\n distance = float(\'inf\')\n for num in arr:\n if abs(target - num) < distance:\n distance = abs(target - num)\n \n return distance\n```\nRuntime: 2392 ms (faster than 93.96%)\nMemory: 14.3 MB (less than 85.71%)
1
0
[]
0
minimize-the-difference-between-target-and-chosen-elements
2 Methods Easy understanding
2-methods-easy-understanding-by-retardin-11jb
\nclass Solution {\npublic:\n int m, n;\n int dp[72][5000];\n int solve(vector<vector<int>>& mat, int row, int sum, const int& target)\n {\n\t\t// B
retarding
NORMAL
2022-03-14T06:32:14.835377+00:00
2022-03-14T06:32:14.835428+00:00
173
false
```\nclass Solution {\npublic:\n int m, n;\n int dp[72][5000];\n int solve(vector<vector<int>>& mat, int row, int sum, const int& target)\n {\n\t\t// Base condition\n if(row >= m)\n {\n return abs(sum - target);\n }\n \n\t\t// Check if already calculated\n if(dp[row][sum] != -1) return dp[row][sum];\n \n int minDiff = INT_MAX;\n for(int i=0; i<n; i++)\n {\n minDiff = min(minDiff, solve(mat, row+1, sum+mat[row][i], target));\n }\n return dp[row][sum] = minDiff;\n }\n \n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n m = mat.size();\n n = mat[0].size();\n memset(dp, -1, sizeof(dp));\n return solve(mat, 0, 0, target);;\n }\n};\n/** Method 2\nclass Solution {\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n bitset<4901>p(1);\n for (auto row : mat) {\n bitset<4901>pp;\n for(auto i:row){\n pp|=(p<<i);\n }\n swap(p,pp);\n }\n \n \n int res = INT_MAX;\n for (int i = 0; i < 4901;i++) {\n if (p[i])res=min(res, abs(i - target));\n }\n return res;\n }\n};\n**/\n```
1
1
['Dynamic Programming', 'Memoization']
0
minimize-the-difference-between-target-and-chosen-elements
Simple Java Solution (Recursion + Memoization)
simple-java-solution-recursion-memoizati-csdr
```\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n int m=mat.length,n=mat[0].length;\n Integer[][] dp=new In
mokshteng
NORMAL
2022-01-07T12:26:46.317845+00:00
2022-01-07T12:26:46.317885+00:00
179
false
```\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n int m=mat.length,n=mat[0].length;\n Integer[][] dp=new Integer[m+1][10000];\n return rec(mat,0,m,n,target,0,dp);\n }\n int rec(int[][] mat,int idx,int m,int n,int target,int sum,Integer dp[][])\n {\n if(idx==m)\n {\n return Math.abs(target-sum);\n }\n if(dp[idx][sum]!=null)\n return dp[idx][sum];\n int min=Integer.MAX_VALUE;\n for(int i=0;i<n;i++)\n {\n min=Math.min(rec(mat,idx+1,m,n,target,mat[idx][i]+sum,dp),min);\n }\n return dp[idx][sum]=min;\n }\n}
1
1
[]
1
minimize-the-difference-between-target-and-chosen-elements
c++ dp
c-dp-by-dolaamon2-d7yx
\nclass Solution {\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n int n = mat.size();\n int m = mat[0].size();\
dolaamon2
NORMAL
2021-11-27T01:23:15.800996+00:00
2021-11-27T01:23:15.801021+00:00
225
false
```\nclass Solution {\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n int n = mat.size();\n int m = mat[0].size();\n bool v[801][2] = {0};\n v[0][0] = 1;\n int mt = 1000000;\n for(int i=n-1; i>=0; i--)\n {\n mt = mt + (*min_element(mat[i].begin(),mat[i].end()));\n for(int k=0; k<=target; k++)\n {\n if (v[k][0])\n {\n for(int j=0; j<m; j++)\n {\n if (mat[i][j] + k <= target)\n v[mat[i][j] + k][1] = true;\n else\n mt = min(mt, mat[i][j] + k);\n }\n }\n }\n for(int i=0; i<=target; i++) \n {\n v[i][0] = v[i][1];\n v[i][1] = false;\n }\n }\n int ans = mt - target; \n for(int i=0; i<=target; i++) \n {\n if (v[i][0])\n ans = min(ans, target-i);\n }\n return ans;\n }\n};\n```
1
0
[]
0
minimize-the-difference-between-target-and-chosen-elements
C++| Top-Down with pruning | DP + memoization
c-top-down-with-pruning-dp-memoization-b-jcyn
\n\n\nclass Solution {\npublic:\n int dp[5000][71]; \n int n, m, target; \n vector<vector<int>> mat;\n int res = INT_MAX; \n int memo(int row, in
aditya_trips
NORMAL
2021-10-20T13:35:43.260253+00:00
2021-10-20T13:36:13.301753+00:00
304
false
\n\n```\nclass Solution {\npublic:\n int dp[5000][71]; \n int n, m, target; \n vector<vector<int>> mat;\n int res = INT_MAX; \n int memo(int row, int currSum){\n if(row == n){\n res = min(res , abs(currSum-target)); \n return abs(currSum-target); \n }\n if(dp[currSum][row] != -1) return dp[currSum][row] ; \n if((currSum-target) > res) return 1e9; \n \n int res = INT_MAX; \n for(int j=0; j<m; j++){\n res = min(res, memo(row+1, currSum+mat[row][j])); \n }\n \n return dp[currSum][row] = res ; \n \n }\n \n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n n = mat.size(), m = mat[0].size(); \n this->target = target; \n this->mat = mat; \n memset(dp, -1,sizeof(dp));\n memo(0, 0);\n return res ;\n }\n};\n```
1
0
['Dynamic Programming', 'Memoization', 'C']
0
minimize-the-difference-between-target-and-chosen-elements
Python DP Solution with prunning, beats ~80%
python-dp-solution-with-prunning-beats-8-63ek
At each row, dp[i] is a list of unique sums we can obtain considering rows up to and including i.\ndp[i] = set(d+el for el in row for d in dp[i-1])\n\nNotice th
niteloser
NORMAL
2021-09-03T12:03:52.871385+00:00
2021-09-03T12:03:52.871429+00:00
203
false
At each row, dp[i] is a list of unique sums we can obtain considering rows up to and including i.\n`dp[i] = set(d+el for el in row for d in dp[i-1])`\n\nNotice the following: for each element `el` of row, if we `d+el >= target` for some `d` in `dp[i-1]` , there is no need to consider values of `dp[i-1]` that are greater than `d`. This is because all elements of `mat` are positive, and including solutions that are larger than `target` at row `i` can only increase the absolute difference when including subsequent rows. In this case, `d+el` could still be part of the optiomal solution, so we include it.\n\n```\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n diff = [0]\n\n for row in mat:\n new_diff = set()\n for el in row:\n for d in diff:\n new_diff.add(d+el)\n if d+el >= target:\n break\n diff = list(new_diff)\n diff.sort()\n \n ret = None\n for d in diff:\n abs_diff = abs(target-d)\n if ret is None:\n ret = abs_diff\n ret = min(ret, abs_diff)\n \n return ret \n```\n
1
0
[]
0
minimize-the-difference-between-target-and-chosen-elements
Two solutions: iterative DP, and dfs with memo
two-solutions-iterative-dp-and-dfs-with-4399t
For iterative dp, at each row we update all possible sum of values we can get. \nFor example, if we at row r, we want to see what sum of values we have at row r
paullyu
NORMAL
2021-09-01T19:45:14.270824+00:00
2021-09-01T19:45:14.270856+00:00
293
false
For iterative dp, at each row we update all possible sum of values we can get. \nFor example, if we at row r, we want to see what sum of values we have at row r-1,\nand we can append mat numbers at row r to sum of values end at row r - 1 to form new\nsum of values\n\ndp[i] means if value i can be formed at current row\n```class Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n int maxVal = 70 * mat.length;\n boolean[] dp = new boolean[maxVal + 1];\n dp[0] = true;\n for (int r = 0; r < mat.length; r++) {\n boolean[] dp2 = new boolean[maxVal + 1];\n for (int c = 0; c < mat[0].length; c++) {\n for (int val = mat[r][c]; val <= maxVal; val ++) {\n dp2[val] = dp2[val] || dp[val - mat[r][c]];\n }\n }\n dp = dp2;\n }\n \n int res = Integer.MAX_VALUE;\n for (int val = 0; val <= maxVal; val++) {\n if (dp[val]) {\n res = Math.min(res, Math.abs(target - val));\n }\n }\n return res;\n }\n}\n```\n\n\nSecond method is DFS with memo. Hight level idea of memo is always find and model depulication.\nDeplicate here is: at a sepcific row, we have a same accumulative sum via different dfs path. So this \ndifferent dfs path lead to a same condition. \n```\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n int[][] memo = new int[mat.length][4901];\n for (int[] arr : memo) {\n Arrays.fill(arr, -1);\n }\n return dfs(mat, 0, 0, target, memo);\n }\n \n private int dfs(int[][] mat, int index, int val, int target, int[][] memo) {\n if (index == mat.length) {\n return Math.abs(val - target);\n }\n if (memo[index][val] != -1) {\n return memo[index][val];\n }\n int res = Integer.MAX_VALUE;\n for (int c = 0; c < mat[0].length; c++) {\n res = Math.min(res, dfs(mat,index + 1, val + mat[index][c], target, memo));\n }\n memo[index][val] = res;\n return res;\n }\n}\n```
1
0
[]
1
minimize-the-difference-between-target-and-chosen-elements
My Java Solution using Memoization
my-java-solution-using-memoization-by-vr-gxk5
\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n if (mat == null || mat.length == 0 || target < 0)\n retu
vrohith
NORMAL
2021-08-26T18:47:53.049363+00:00
2021-08-26T18:47:53.049434+00:00
443
false
```\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n if (mat == null || mat.length == 0 || target < 0)\n return -1;\n int row = mat.length;\n int col = mat[0].length;\n // 70 * 70\n // [index][available sum]\n Integer [][] memo = new Integer [row][70 * 70 + 1];\n return minimumPossible(mat, target, 0, 0, memo);\n }\n \n public int minimumPossible(int [][] mat, int target, int currentRowIndex, int currentSum, Integer [][] memo) {\n if (currentRowIndex == mat.length) {\n return Math.abs(currentSum - target);\n }\n if (memo[currentRowIndex][currentSum] != null) {\n return memo[currentRowIndex][currentSum];\n } \n int eachRowResult = Integer.MAX_VALUE;\n for (int colIndex = 0; colIndex < mat[0].length; colIndex++) {\n eachRowResult = Math.min(eachRowResult, minimumPossible(mat, target, currentRowIndex + 1, currentSum + mat[currentRowIndex][colIndex], memo));\n }\n return memo[currentRowIndex][currentSum] = eachRowResult;\n }\n}\n```
1
0
['Recursion', 'Memoization', 'Java']
1
minimize-the-difference-between-target-and-chosen-elements
(C++) 1981. Minimize the Difference Between Target and Chosen Elements
c-1981-minimize-the-difference-between-t-d6ea
\n\nclass Solution {\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n bitset<5000> bits(1); \n for (auto& row : m
qeetcode
NORMAL
2021-08-24T21:41:09.745617+00:00
2021-08-24T21:43:11.257473+00:00
260
false
\n```\nclass Solution {\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n bitset<5000> bits(1); \n for (auto& row : mat) {\n bitset<5000> temp; \n for (auto& x : row) temp |= (bits << x); \n bits = temp; \n }\n \n for (int x = 0; ; ++x) \n if (bits[target+x] || (x <= target && bits[target-x])) return x; \n return -1; \n }\n};\n```
1
0
['C']
0
minimize-the-difference-between-target-and-chosen-elements
C++ | Recursion + Memoization | Knapsack Variation
c-recursion-memoization-knapsack-variati-qyn4
\nclass Solution {\npublic:\n \n int dp[75][4900+805];\n int cnt=70*70;\n int solve(int i,vector<vector<int>>& mat,int t)\n {\n \n
abhi_code_1
NORMAL
2021-08-24T14:43:08.097195+00:00
2021-08-24T15:05:54.632837+00:00
335
false
```\nclass Solution {\npublic:\n \n int dp[75][4900+805];\n int cnt=70*70;\n int solve(int i,vector<vector<int>>& mat,int t)\n {\n \n if(i==mat.size())\n {\n return abs(t);\n }\n \n if(dp[i][cnt+t]!=-1)return dp[i][cnt+t];\n int mn=1e9;\n for(auto j:mat[i])\n {\n mn=min(mn,solve(i+1,mat,t-j));\n \n }\n \n return dp[i][cnt+t]=mn;\n }\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n \n memset(dp,-1,sizeof(dp));\n \n return solve(0,mat,target);\n }\n};\n```
1
1
['Recursion', 'Memoization']
1
minimize-the-difference-between-target-and-chosen-elements
C++ / DP / Memoization
c-dp-memoization-by-hitesh2494-ybmh
c++\nclass Solution {\npublic:\n /*\n Over here we are given that the size of the input array won\'t exceed 70. We want to get the sum using each posiible
hitesh2494
NORMAL
2021-08-23T07:53:14.810705+00:00
2021-08-23T07:53:14.810753+00:00
74
false
```c++\nclass Solution {\npublic:\n /*\n Over here we are given that the size of the input array won\'t exceed 70. We want to get the sum using each posiible combination. But we won\'t calculate the sum that is already compyed for a give row. \n */\n //this is how we initialize an array in a range with some specified value.\n //Also we like to take a buffer size with one extra space.\n int cache[71][70*70 + 1] = {[0 ... 70][0 ... 70*70] = -1};\n \n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n //In order to optimize our computation we can store the matrix in a set. That way we won\'t have to deal with the duplicate entries. \n vector<set<int>> matrix;\n for(auto &row : mat)\n {\n matrix.push_back(set<int>(row.begin(), row.end()));\n }\n \n return findMinSum(matrix, 0, 0, target);\n }\n \n int findMinSum(vector<set<int>>& mat, int row, int sum, int target)\n {\n if(row >= mat.size())\n {\n return abs(target-sum);\n }\n \n if(cache[row][sum] != -1)\n return cache[row][sum];\n \n int ans = INT_MAX;\n //We need to iterate over each row and since row is a set, we need an iterator.\n for(auto it = mat[row].begin(); it!=mat[row].end(); it++)\n {\n ans = min(ans, findMinSum(mat, row+1, sum + *it, target));\n \n //we can further optimize out algorithm here with this check.\n //\n if(cache[row][sum] == 0 || sum + *it > target)\n break;\n }\n \n return cache[row][sum] = ans;\n }\n};\n```\n
1
0
[]
0
minimize-the-difference-between-target-and-chosen-elements
[C++] bitset with explanations, 76ms, faster than 100%,
c-bitset-with-explanations-76ms-faster-t-jg4s
Bitset could be a good choic to this question:\n1. the sums are in a relative small range (<5000);\n2. use the index of the bitset to represent the possible sum
dingdang2014
NORMAL
2021-08-22T22:53:11.716326+00:00
2021-08-22T23:36:09.935351+00:00
134
false
Bitset could be a good choic to this question:\n1. the sums are in a relative small range (<5000);\n2. use the index of the bitset to represent the possible sum;\n3. use the bit shift operation to greatly reduce the time complexity. Only one shift operation can be equivalent to add a number to all the sums stored in the bitset.\n\nMore explanations can be found [https://algorithm-notes-allinone.blogspot.com/2021/08/leetcode-1981-minimize-difference.html](http://),\n\n\n```\nclass Solution {\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n int m = mat.size(), n = mat.front().size(), cs = 5000, res = cs;\n bitset<5000> bt;\n for(int i=0; i<n; ++i) bt[mat[0][i]] = 1;\n for(int i=1; i<m; ++i) {\n bitset<5000> pre = bt, nxt;\n for(int j=0; j<n; ++j) {\n nxt |= pre << mat[i][j];\n }\n bt = nxt;\n }\n for(int i=0; i<cs; ++i) {\n if(bt[i]) res = min(res, abs(i-target));\n }\n return res;\n }\n};\n```
1
0
['Bit Manipulation']
1
minimize-the-difference-between-target-and-chosen-elements
[Python] Optimized brute force in O(target * n * n) time and O(target) space, explained
python-optimized-brute-force-in-otarget-5jxr3
If you try to solve this with Brute-force, the run time would be O(n^n), and you would always get TLE.\n\nMy optimization is still to add the nums row by row, h
h241668288
NORMAL
2021-08-22T15:33:40.670717+00:00
2021-08-22T15:49:58.693043+00:00
156
false
If you try to solve this with Brute-force, the run time would be O(n^n), and you would always get TLE.\n\nMy optimization is still to add the nums row by row, however, use a set call "to_visit" to track the "valid" numbers that can be brought to the next row. The valid number will be **all nums smaller than the target** plus **the smallest number that is larger than the target.** The logic is as follows:\n\n1. Every smaller number in the to_visit set plus the numbers in the next row may be closer to your target.\n2. The smallest larger number could be the only candidate that will be close to the target after the operation with the next row.\n\nUsing the example \n\n[[1,2,3],[4,5,6],[7,8,9]]\n13\n\nwhat you get each time in to_visit will be\n{1, 2, 3}\n{5, 6, 7, 8, 9}\n{12, 13, 14} (you can get 15,16,17,18, but they are not the smallest larger num, so you can disgard them, we only keep 14 here)\n\nOnce you finsh iteration through the matrix, you can find the closest value in the last to_visit set with time of O(target), in the worst case.\n\nI guess...Overall time complexity O(target * n * n) ), \nas the worst case scenario what you need to add to the to_vist would be target * n numbers, and you may need to repeat it for n times.\n\nOverall space complexity O(target), \nas you only need to maintain the to_visit set, which has worst case size of the target + 1\n```\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n to_visit = {0}\n for row in mat:\n larger_val = math.inf\n temp = to_visit.copy()\n to_visit = set()\n for num in set(row): \n for item in temp:\n if num + item <= target:\n to_visit.add(num + item)\n else:\n larger_val = min(larger_val, num + item)\n if larger_val != math.inf:\n to_visit.add(larger_val)\n ans = math.inf\n for i in to_visit:\n ans = min(abs(target - i),ans)\n return ans\n \n \n```
1
0
['Ordered Set', 'Python']
0
minimize-the-difference-between-target-and-chosen-elements
C++ DP 100% efficient
c-dp-100-efficient-by-verdict_ac-l0z4
\nclass Solution {\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) \n {\n int m=mat.size(),n=mat[0].size();\n int
Verdict_AC
NORMAL
2021-08-22T09:26:44.587924+00:00
2021-08-22T09:26:44.587952+00:00
137
false
```\nclass Solution {\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) \n {\n int m=mat.size(),n=mat[0].size();\n int dp[m][target+2];\n for(int i=0;i<m;i++)\n for(int j=0;j<=target;j++)\n dp[i][j]=-1;\n for(int i=0;i<m;i++)dp[i][target+1]=INT_MAX;\n for(int i=0;i<n;i++)\n {\n if(mat[0][i]<=target)dp[0][mat[0][i]]=mat[0][i];\n else dp[0][target+1]=min(dp[0][target+1],mat[0][i]); \n }\n for(int i=1;i<m;i++)\n for(int j=0;j<n;j++)\n for(int k=0;k<=target+1;k++)\n {\n if(dp[i-1][k]==-1||dp[i-1][k]==INT_MAX)continue;\n if(k+mat[i][j]>target)\n {\n if(k<=target)dp[i][target+1]=min(dp[i][target+1],k+mat[i][j]);\n else dp[i][target+1]=min(dp[i][target+1],dp[i-1][k]+mat[i][j]);\n }else dp[i][k+mat[i][j]]=k+mat[i][j];\n }\n int ans=INT_MAX;\n for(int i=0;i<=target+1;i++)\n if(dp[m-1][i]!=-1)ans=min(ans,abs(target-dp[m-1][i]));\n return ans;\n }\n};\n```
1
0
['Dynamic Programming']
0
minimize-the-difference-between-target-and-chosen-elements
[C++] DP solution with explanation
c-dp-solution-with-explanation-by-manish-f9i9
Actually, we need to find a range of sum on which we can apply DP.\n So find the sum of smallest element(let say s) from each row. If this sum is greater than o
manishbishnoi897
NORMAL
2021-08-22T08:29:46.980969+00:00
2021-08-22T08:39:25.329824+00:00
189
false
* Actually, we need to find a range of sum on which we can apply DP.\n* So find the sum of smallest element(let say s) from each row. If this sum is greater than or equal to the target`(s>=target)`, then no other better solution exists and `abs(target-s)` will be our answer.\n\tFor eg. Let the sum we got from smaller elements is 450 and target is 400. All the other sum in the matrix will be greater than 450 and hence the absolute difference will increase.\n* If s < target, then we have to find a range on which we can apply DP. The `lower bound of this range will definitely be s`. `The upper bound will be target + abs(target-s)`. Above this, we will not be getting a better answer.\n* So the last step is to run a loop on this range and we will find that the particular sum exist or not in the matrix using DP.\n\n```\nclass Solution {\n int dp[71][3001];\n\t// DP to find a particular sum exist or not \n bool helper(int sum,int m,int n,vector<vector<int>>& mat){\n if(m==0 && sum==0){\n return true;\n }\n if(m==0 || sum<0){\n return false;\n }\n if(dp[m][sum]!=-1){\n return dp[m][sum];\n }\n for(int i=0;i<n;i++){\n if(mat[m-1][i]>sum) continue;\n bool check = helper(sum-mat[m-1][i],m-1,n,mat);\n if(check){\n return dp[m][sum]=true; \n } \n }\n return dp[m][sum]=false;\n }\n\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n memset(dp,-1,sizeof dp);\n int ans=INT_MAX;\n int s=0,m =mat.size(),n=mat[0].size();\n\t\t// Finding sum of smallest element from each row\n for(int i =0;i<m;i++){\n int y=INT_MAX;\n for(int j=0;j<n;j++){\n y=min(y,mat[i][j]);\n }\n s+=y;\n }\n if(s>=target){\n return abs(s-target);\n }\n int x = abs(s-target); // Upper limit\n\t\t// Running loop over the range\n for(int i=s;i<target+x;i++){\n if(helper(i,m,n,mat)){\n ans=min(ans,abs(target-i));\n }\n }\n return ans;\n }\n};\n```\n**Hit Upvote if you like :)**
1
0
['Dynamic Programming', 'C']
0
minimize-the-difference-between-target-and-chosen-elements
[Java] Use HashSet at every row to find every possible value
java-use-hashset-at-every-row-to-find-ev-gb3x
\n\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n HashSet<Integer>set=new HashSet();\n int m=mat.length, n=m
bryantt23
NORMAL
2021-08-22T07:15:20.659813+00:00
2021-08-22T07:15:20.659845+00:00
69
false
```\n\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n HashSet<Integer>set=new HashSet();\n int m=mat.length, n=mat[0].length;\n \n // get every value in the row\n for(int j=0; j<n; j++){\n set.add(mat[0][j]);\n }\n \n for(int i=1; i<m; i++){\n HashSet<Integer>newSet=new HashSet();\n HashSet<Integer>row=new HashSet();\n \n // get every value in the row\n for(int j=0; j<n; j++){\n row.add(mat[i][j]);\n }\n \n for(int k: set){\n for(int r: row){\n // get every value so far \n newSet.add(r+k);\n }\n }\n set=new HashSet(newSet);\n }\n \n int min=Integer.MAX_VALUE;\n \n for(int i: set){\n min=Math.min(min, Math.abs(target-i));\n }\n \n return min; \n }\n}\n```
1
0
[]
1
minimize-the-difference-between-target-and-chosen-elements
C++ bitset 100%
c-bitset-100-by-colinyoyo26-fb5m
\nclass Solution {\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n bitset<5000> b, b1; \n b.set(0);\n for
colinyoyo26
NORMAL
2021-08-22T07:04:16.530024+00:00
2021-08-22T07:04:16.530065+00:00
94
false
```\nclass Solution {\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n bitset<5000> b, b1; \n b.set(0);\n for (auto &v : mat) {\n for (auto a : v)\n b1 |= b << a;\n swap(b, b1);\n b1.reset();\n }\n int ans = INT_MAX;\n for (int i = 0; i < 5000; i++) \n if (b[i]) ans = min(ans, abs(i - target));\n\t\treturn ans;\n\t\t\n \n }\n};\n\n```
1
0
[]
0
minimize-the-difference-between-target-and-chosen-elements
[Java] DP solution with greedy.
java-dp-solution-with-greedy-by-lincansh-jmp4
\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n int min_sum = 0;\n for (int[] row : mat) {\n int
lincanshu
NORMAL
2021-08-22T04:26:00.683425+00:00
2021-08-22T04:26:08.115026+00:00
182
false
```\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n int min_sum = 0;\n for (int[] row : mat) {\n int min = Integer.MAX_VALUE;\n for (int num : row) {\n min = Math.min(num, min);\n }\n min_sum += min;\n }\n int threshold = Math.abs(min_sum - target);\n\n Set<Integer> lastRow = new HashSet<>();\n lastRow.add(target);\n for (int[] row : mat) {\n boolean[] array = new boolean[71];\n for (int num : row) {\n array[num] = true;\n }\n Set<Integer> curRow = new HashSet<>();\n for (int i = 1; i <= 70; i++) {\n if (array[i]) {\n for (int val : lastRow) {\n if (val - i < -target) continue;\n curRow.add(val - i);\n }\n }\n }\n lastRow = curRow;\n }\n int res = threshold;\n for (int val : lastRow) {\n res = Math.min(res, Math.abs(val));\n }\n return res;\n }\n}\n```
1
0
['Java']
0
minimize-the-difference-between-target-and-chosen-elements
Answer Giving TLE please tell the error like I am unable to figure it out
answer-giving-tle-please-tell-the-error-4gby2
typedef long long int ll;\nclass Solution {\npublic:\n ll minimizeTheDifference(vector>& mat, ll target) \n\t{\n\t\tll n=mat.size(),m=mat[0].size();\n
patanahikaunheye
NORMAL
2021-08-22T04:22:48.634067+00:00
2021-08-22T04:22:48.634096+00:00
149
false
typedef long long int ll;\nclass Solution {\npublic:\n ll minimizeTheDifference(vector<vector<int>>& mat, ll target) \n\t{\n\t\tll n=mat.size(),m=mat[0].size();\n if(n==0||m==0)\n {\n return target;\n }\n vector<vector<ll>>dp(n+5,vector<ll>(5000,0));\n for(ll i=0;i<=n;i++)\n {\n for(ll j=0;j<=4900;j++)\n dp[i][j]=0;\n }\n ll x=-1;\n for(ll i=0;i<n;i++)\n {\n for(ll j=0;j<m;j++)\n {\n if(i==0)\n {\n dp[i][mat[i][j]]=1;\n }\n else\n {\n for(ll k=1;k<=4900;k++)\n {\n\t\t\t\t\t\tif(dp[i-1][k]==1)\n {\n if(k+mat[i][j]<=4900)\n dp[i][k+mat[i][j]]=1;\n }\n }\n }\n }\n }\n ll ns=0;\n for(ll i=0;i<n;i++)\n {\n ll mini=70;\n for(ll j=0;j<m;j++)\n {\n mini=min(mini,(ll)mat[i][j]);\n }\n ns+=mini;\n }\n ll ans=llabs(ns-target);\n for(ll i=1;i<=4900;i++)\n {\n if(dp[n-1][i]==1)\n {\n ans=min(ans,llabs(target-i));\n }\n }\n return ans;\n }\n};
1
0
[]
0
minimize-the-difference-between-target-and-chosen-elements
[JavaScript] Dynamic Programming
javascript-dynamic-programming-by-steven-2ns0
javascript\n/**\n * Collect all the possible sums but keep only one sum that is greater than the target\n */\nvar minimizeTheDifference = function(mat, target)
stevenkinouye
NORMAL
2021-08-22T04:02:31.773852+00:00
2021-08-30T00:22:19.064116+00:00
348
false
```javascript\n/**\n * Collect all the possible sums but keep only one sum that is greater than the target\n */\nvar minimizeTheDifference = function(mat, target) {\n let possibleSums = new Set(mat[0]);\n for (let row = 1; row < mat.length; row++) {\n const nextPossibleSums = new Set();\n let min = Infinity;\n for (let col = 0; col < mat[row].length; col++) {\n for (const num of possibleSums) {\n const sum = num + mat[row][col];\n // if sum is smaller than the min then it could be the best sum\n if (sum < min) {\n nextPossibleSums.add(sum);\n // if the sum is greater than or equal to the target and\n // less than the min we know the previous min can not be\n // a better sum so we can delete it from the possible sums\n if (sum >= target) {\n nextPossibleSums.delete(min);\n min = sum;\n }\n }\n }\n }\n possibleSums = nextPossibleSums;\n }\n for (let i = 0; i < Infinity; i++) {\n if (possibleSums.has(target + i) || possibleSums.has(target - i)) {\n return i;\n }\n }\n};\n```
1
0
['JavaScript']
0
minimize-the-difference-between-target-and-chosen-elements
c++ bitset
c-bitset-by-harshitata404-p651
IntuitionWe just need to maintain the total unique sums obtained in prev rowApproachSince constraints are small, we are able to use a bitset hereCode
harshitata404
NORMAL
2025-04-07T17:21:26.637665+00:00
2025-04-07T17:21:26.637665+00:00
2
false
# Intuition We just need to maintain the total unique sums obtained in prev row # Approach Since constraints are small, we are able to use a bitset here # Code ```cpp [] class Solution { public: int minimizeTheDifference(vector<vector<int>>& mat, int target) { bitset<10001>prev(1); for(int i=0;i<mat.size();i++){ bitset<10001>curr(0); for(auto n:mat[i]){ curr = curr | (prev<<n); } prev = curr; } int mx = INT_MAX; if(prev[target])return 0; int left = target-1, right = target+1; while(left>=0 && right<1e6+1){ if(prev[left])return target-left; if(prev[right])return right-target; left--; right++; } while(left>=0){ if(prev[left])return target-left; left--; } while(right<1e4+1){ if(prev[right])return right-target; right++; } return mx; } }; ```
0
0
['C++']
0
minimize-the-difference-between-target-and-chosen-elements
Python | C++ DP appropriate knapsack
python-c-dp-appropriate-knapsack-by-kalu-ujqz
Complexity Time complexity: O(NM|K|) Space complexity: |K| Code
kaluginpeter
NORMAL
2025-04-07T09:01:53.268901+00:00
2025-04-07T09:01:53.268901+00:00
12
false
# Complexity - Time complexity: O(NM|K|) - Space complexity: |K| # Code ```python3 [] class Solution: def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int: sums: set[int] = {0} for row in mat: sums = {prev_sum + num for num in row for prev_sum in sums} return min(abs(target - mat_sum) for mat_sum in sums) ``` ```cpp [] class Solution { public: int minimizeTheDifference(vector<vector<int>>& mat, int target) { int n = mat.size(), m = mat[0].size(), K = 4901; vector<bool> prevDp (K, false); vector<bool> curDp (K, false); prevDp[0] = true; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { for (int k = K - mat[i][j] - 1; k >= 0; --k) { if (prevDp[k]) { curDp[k + mat[i][j]] = true;; } } } prevDp = curDp; curDp = vector<bool> (K, false); } int minDiff = INT32_MAX; for (int k = 0; k < K; ++k) { if (prevDp[k]) { int diff = abs(target - k); minDiff = min(minDiff, diff); } } return minDiff; } }; ```
0
0
['Array', 'Dynamic Programming', 'Matrix', 'C++', 'Python3']
0
minimize-the-difference-between-target-and-chosen-elements
This shouldn't have worked but it does...
this-shouldnt-have-worked-but-it-does-by-gh5v
Code
Erohblak
NORMAL
2025-04-07T07:19:04.085757+00:00
2025-04-07T07:29:15.794927+00:00
7
false
# Code ```cpp [] class Solution { public: int minimizeTheDifference(vector<vector<int>>& mat, int target) { int n = mat.size(); int m = mat[0].size(); int ans = INT_MAX; int minSum = 0, maxSum = 0; for (int i = 0; i < mat.size(); i++) { minSum += *min_element(mat[i].begin(), mat[i].end()); maxSum += *max_element(mat[i].begin(), mat[i].end()); } // return if target is out of range [minimum possible sum, maximum possible sum] if (target <= minSum) { return minSum - target; } if (target >= maxSum) { return target - maxSum; } ans = min({ans, target - minSum, maxSum - target}); set<int> possibleTargets; // possible target sums in the first row for (int col = 0; col < mat[0].size(); col++) { possibleTargets.insert(mat[0][col]); } for (int row = 1; row < n; row++) { set<int> currTarget; // targets for each row will be initialised here for (int col = 0; col < m; col++) { int num = mat[row][col]; for (auto x: possibleTargets) { if (x + num > target + 5) { // special condition to avoid TLE xD continue; // if next possible target is slightly bigger than the actual target } // then don't add it to the possible targets currTarget.insert(x + num); // add the new target to this row } } possibleTargets = currTarget; // reset the targets with current row's targets, // so when iterating on last row, we will have actual possible targets } // return the closest value to actual possible targets for (auto val : possibleTargets) { ans = min(ans, abs(val - target)); } return ans; } }; ```
0
0
['C++']
0
minimize-the-difference-between-target-and-chosen-elements
Moving Sum Set
moving-sum-set-by-lilongxue-up95
IntuitionUse a moving sum set.Approach The sum set initially is the first row. Go down row by row, and for each row, we update the sum set. In the final sum set
lilongxue
NORMAL
2025-04-02T03:29:16.669743+00:00
2025-04-02T03:29:16.669743+00:00
1
false
# Intuition Use a moving sum set. # Approach 1. The sum set initially is the first row. 2. Go down row by row, and for each row, we update the sum set. 3. In the final sum set, find the closet sum along with its difference. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {number[][]} mat * @param {number} target * @return {number} */ var minimizeTheDifference = function(mat, target) { const R = mat.length, C = mat[0].length let sumSet = new Set(mat[0]) for (let i = 1; i < R; i++) { const sumSetNext = new Set() const row = new Set(mat[i]) for (const val of row) { for (const sum of sumSet) { const sumNext = val + sum sumSetNext.add(sumNext) } } sumSet = sumSetNext } let result = Infinity for (const sum of sumSet) { const outcome = Math.abs(sum - target) result = Math.min(result, outcome) } return result }; ```
0
0
['JavaScript']
0
minimize-the-difference-between-target-and-chosen-elements
Simple bitmask solution
simple-bitmask-solution-by-lilysunstride-mte1
IntuitionBitmask is good at storing all possible values within a small rangeApproach loop through the matrix to record all possible values find the distance bet
lilysunstrider
NORMAL
2025-03-10T17:57:02.566548+00:00
2025-03-10T17:57:02.566548+00:00
4
false
# Intuition Bitmask is good at storing all possible values within a small range # Approach - loop through the matrix to record all possible values - find the distance between target and possible values <!-- Describe your approach to solving the problem. --> # Code ```typescript [] function minimizeTheDifference(mat: number[][], target: number, row = 0): number { let possibleResults = 1n; for (const row of mat) { let thisResults = 0n; for (const num of row) { thisResults |= possibleResults << BigInt(num); } possibleResults = thisResults; } let targetMask = 1n << BigInt(target); let difference = 0; while (!(targetMask & possibleResults)) { targetMask = (targetMask << 1n) | (targetMask >> 1n); difference += 1; } return difference; }; ```
0
0
['TypeScript']
0
minimize-the-difference-between-target-and-chosen-elements
Most Optimal Time (O(N*M*M) and Space Complexity (2*O(M*M))
most-optimal-time-onmm-and-space-complex-6rsr
ApproachAssume that N = num of rows, and M = num of colsWe start with inserting our base case into our current Set, since if we assume the matrix is of zero row
varunadit2
NORMAL
2025-03-08T19:48:30.200325+00:00
2025-03-08T19:48:30.200325+00:00
3
false
# Approach <!-- Describe your approach to solving the problem. --> Assume that N = num of rows, and M = num of cols We start with inserting our base case into our current Set, since if we assume the matrix is of zero rows and zero columns, we would be able to achieve only one sum that is Zero. Building upon our base case, if the matrix only had one row, we would be achieve M possible candidates for addition within the first row. Adding these with all possible sums of previous row, we get M * (prev row's possible sums).count new sums for 1st row. Building upon this same logic, we would have a maximum of 70 * 70 sums when we finish adding elements of the final row to all possible sums possible within N-1th row. Now it's just a matter of computing the absolute difference between target and each of the final sums and returning the minimum absolute difference # Complexity Assume that N = num of rows, and M = num of cols - Time complexity: O(N * M * M) - Space complexity: 2*O(M * M) # Code ```swift [] class Solution { func minimizeTheDifference(_ mat: [[Int]], _ target: Int) -> Int { let rows = mat.count var prev = Set<Int>() var cur = Set<Int>() cur.insert(0) for i in 0..<rows { prev = cur cur = [] for sum in prev { for num in mat[i] { cur.insert(sum + num) } } } var minDiff = Int.max for sum in cur { minDiff = min(minDiff, abs(sum - target)) } return minDiff } } ```
0
0
['Dynamic Programming', 'Swift']
0
minimize-the-difference-between-target-and-chosen-elements
C++ Solution by dp and bitset with clear explanation
c-solution-by-dp-and-bitset-with-clear-e-ns26
Complexity Time Complexity: O(n∗m) Space Complexity: O(1) IdeaWe use the bitset seen to record the sum that we have seen, seen[i]=1 if and only if we have seen
tan5166
NORMAL
2025-01-27T04:03:57.850935+00:00
2025-01-27T04:05:30.313443+00:00
11
false
## Complexity - Time Complexity: $O(n * m)$ - Space Complexity: $O(1)$ ## Idea We use the bitset `seen` to record the sum that we have seen, $seen[i] = 1$ if and only if we have seen the sum $i$. By this idea, we first set $seen[0]= 1$. When there is a new number, say $num$, and we want to find all of its possible sum with the previous recorded sum, we can just simply use $seen << num$. Hence, we have the following code: ````c++ int n = mat.size(); int m = mat[0].size(); bitset<70 * 70 + 1> seen; //this is because mat[i][j]<=70 and n <= 70, so the largest sum is 70*70. seen[0] = 1; for(auto& row : mat){ bitset<70 * 70 + 1> new_seen; for(int num : row){ new_seen |= (seen << num); } seen = new_seen; } ```` After this, we start by looking around $seen[target]$ to find the number closest to it. ````C++ for(int i = 0; i<=target; i++){ if(seen[target + i] || seen[target - i]){ return i; } } for(int i = target + 1; i < 4901; i++){ if(seen[target + i]) return i; } ```` # Code ```cpp [] class Solution { public: int minimizeTheDifference(vector<vector<int>>& mat, int target) { int n = mat.size(); int m = mat[0].size(); bitset<70 * 70 + 1> seen; //this is because mat[i][j]<=70 and n <= 70, so the largest sum is 70*70. seen[0] = 1; for(auto& row : mat){ bitset<70 * 70 + 1> new_seen; for(int num : row){ new_seen |= (seen << num); } seen = new_seen; } for(int i = 0; i<=target; i++){ if(seen[target + i] || seen[target - i]){ return i; } } for(int i = target + 1; i < 4901; i++){ if(seen[target + i]) return i; } return -1; } }; ```
0
0
['C++']
0
minimize-the-difference-between-target-and-chosen-elements
DFS + Optimisation / Pruning
dfs-optimisation-pruning-by-matt_scott-srls
IntuitionGiven the constraints of this problem, it's not unrealistic to expect that we can use DP / recursion to (intelligently) brute-force the solution. Recur
matt_scott
NORMAL
2025-01-24T15:40:36.091646+00:00
2025-01-24T15:40:36.091646+00:00
11
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Given the constraints of this problem, it's not unrealistic to expect that we can use DP / recursion to (intelligently) brute-force the solution. Recursively, we can take a number in each row, and ask for the reduced problem of `target - mat[i][j]` for the next recursive call, starting at the next row. The difficulty is with the complexity: we would need to try every row (`i`) for every column (`j`), with all possible target sums (`k`), giving $O(i*j*k)$ which would technically pass, although there are improvements that can be made: # Approach <!-- Describe your approach to solving the problem. --> - Base Approach: $\forall i\forall j\forall k: f(i,k) = min(f(i+1, k - j))$ - Remove Duplicates: There is no point reconsidering duplicates in a row, as they will lead to the same solution - Binary Search: The maximum value in a row we can use is bound by the target. I.e., if our target is 14, there is no point considering values greater than 14 in a particular row. By sorting each row, we can perform a binary search to find the maximum value of `j` - Prefix Sums: If our target every goes negative, then we may as well choose all of the smallest values to minimise the 'damage'. Keeping a prefix sum of all the smallest values lets us work out $\sum_i^Mmat[i][0]$ efficiently - Caching/Memoisation: there is no point in recalculating similar functions. We should cache all of our function results These techniques will improve the average run time, but not the complexity (i.e., the worst-case performance) # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> $$O(m*n*k)$$ - We need to consider every row in the matrix, for every column, for every target value - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> $$O(m*k)$$ - we cache all values for each row, for each target value # Code ```python3 [] class Solution: def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int: M = len(mat) # remove duplicates and sort row for binary search for i in range(M): mat[i] = sorted(set(mat[i])) # prefix array for getting smallest sum at index onwards pref = [0] for i in range(M): pref.append(pref[-1] + mat[i][0]) @cache def dfs(i, curr): if i == M: return abs(curr) if curr < 0: rest = pref[-1] - pref[i] return abs(curr - rest) ans = float("inf") N = len(mat[i]) maxIdx = min(N-1, bisect_right(mat[i], curr)) for j in range(maxIdx, -1, -1): ans = min(ans, dfs(i+1, curr - mat[i][j])) return ans return dfs(0, target) ```
0
0
['Python3']
0
minimize-the-difference-between-target-and-chosen-elements
Backtrack + DP with time/space complexity explanation
backtrack-dp-with-timespace-complexity-e-819p
IntuitionBacktracking along with Dynamic Programming+Memorization.ApproachDo DFS. For each element of the row, explore all the elements of next row. Accumulate
sam506
NORMAL
2025-01-18T06:58:27.702107+00:00
2025-01-18T06:58:27.702107+00:00
14
false
# Intuition Backtracking along with Dynamic Programming+Memorization. # Approach Do DFS. For each element of the row, explore all the elements of next row. Accumulate the sum and capture the min results if the current row is the last row. Optimization step: If the sum has gone bigger than the target, and the diff is more than the already found min results, stop the recursion. (Rational is, all the elements in the matrix are +ve. So, the sum keeps growing row after row. So, the sum at some row is already bigger than the target and diff is bigger than already found mis results - there's no point continuing - the diff will grow bigger and bigger - it wont be the min solutions anyway - so stop the recursion.) It is this line: ``` if (sum-target >= MIN_DIFF) return; ``` # Complexity - Time complexity: Worstcase O(n^m) DP+Memorization can save time if there are repeated sums. - Space complexity: Max sum = num_rows * max_element_in_matrix So, DP total space is O(m * (m * max_element_in_matrix) ), i.e. O(m^2 * max_element_in_matrix) # Code ```cpp [] class Solution { int MIN_DIFF = INT_MAX; int n=0, m=0; void dfs(int r, int sum, vector<vector<int>> &dp, const vector<vector<int>>& mat, const int target) { // If the sum was alread explored for this row, no need to repeat it. Skip. if (dp[r][sum] != -1) return; // Optimization step: sum has become too high than target (the diff is greter than the min_solution). // (Since all the numnber are +ve) we now know, no point continuing the dfs into next row. Stop here. if (sum-target >= MIN_DIFF) return; // Current row is the last row if(r == n) { MIN_DIFF = min(MIN_DIFF, abs(target-sum)); } else { // Current row is not the last row for(int j = 0; j < m; j++) { dfs(r+1, sum + mat[r][j], dp, mat, target); } } // DP: at row r, sum is explored. dp[r][sum] = 1; return; } public: int minimizeTheDifference(vector<vector<int>>& mat, int target) { n = mat.size(); m = mat[0].size(); vector<vector<int>> dp(n+1, vector<int> (70*70, -1)); dfs(0, 0, dp, mat, target); return MIN_DIFF; } }; ```
0
0
['C++']
0
minimize-the-difference-between-target-and-chosen-elements
Java DP solution
java-dp-solution-by-priyanshiigoyal-6kso
IntuitionApproachThe problem depends on two factors the sum and the row number so using this dpComplexity Time complexity: Space complexity: O(m*S) whre S is
priyanshiigoyal
NORMAL
2025-01-09T15:00:36.519290+00:00
2025-01-09T15:00:36.519290+00:00
12
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach The problem depends on two factors the sum and the row number so using this dp # Complexity - Time complexity: - Space complexity: O(m*S) whre S is sum <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int minimizeTheDifference(int[][] mat, int t) { int m = mat.length; int[][] dp = new int[m][4901]; for(int i=0;i<m;i++){ Arrays.fill(dp[i],Integer.MAX_VALUE); } return diff(mat,0,0,t,dp); } private int diff(int[][] mat,int i, int sum, int t, int[][]dp){ if(i==mat.length) return Math.abs(sum-t); if(dp[i][sum]!=Integer.MAX_VALUE) return dp[i][sum]; for(int j=0;j<mat[0].length;j++){ dp[i][sum] = Math.min(dp[i][sum], diff(mat,i+1,sum+mat[i][j],t,dp)); } return dp[i][sum]; } } ```
0
0
['Dynamic Programming', 'Java']
0
minimize-the-difference-between-target-and-chosen-elements
Simple DP + Memoization solution || c++ || beats 90%
simple-dp-memoization-solution-c-beats-9-7f4q
IntuitionApproachComplexity Time complexity: Space complexity: Code
vikash_kumar_dsa2
NORMAL
2025-01-05T17:09:23.278846+00:00
2025-01-05T17:09:23.278846+00:00
10
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int dp[8000][71]; int solve(vector<vector<int>>& mat,int start,int m,int n,int target,int sum){ if(start >= m){ return abs(target - sum); } if(dp[sum][start]!=-1) { return dp[sum][start]; } int minVal = INT_MAX; for(int i = 0;i<n;i++){ minVal = min(minVal,solve(mat,start+1,m,n,target,sum + mat[start][i])); if(minVal == 0){ break; } } return dp[sum][start] = minVal; } int minimizeTheDifference(vector<vector<int>>& mat, int target) { memset(dp,-1,sizeof(dp)); int m = mat.size(); int n = mat[0].size(); return (solve(mat,0,m,n,target,0)); } }; ```
0
0
['Dynamic Programming', 'Memoization', 'C++']
0
minimize-the-difference-between-target-and-chosen-elements
Python int as bitset in two lines ~15ms
python-int-as-bitset-by-edward-ji-pt0w
ApproachUse a single integer seen as a hash set for the sum we've seen for far. The i-th least significant bit represents whether the sum i is possible. Initial
edward-ji
NORMAL
2025-01-03T16:12:33.871606+00:00
2025-01-04T02:52:33.681044+00:00
13
false
# Approach Use a single integer `seen` as a hash set for the sum we've seen for far. The `i`-th least significant bit represents whether the sum `i` is possible. Initially, `seen = 1` represents that the sum `0` is possible by not taking any number. For each `num` in each row, we compute the new possible sums by left shifting the seen sums from the previous row by `num`. At last, we can find the set bit that's closest to the `target`-th bit, for it is the closest sum to `target`. # Code ```python3 [Two&hyphen;liner] class Solution: def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int: seen = reduce(lambda seen, row: reduce(operator.or_, (seen << num for num in set(row))), mat, 1) return next(diff for diff in count() if (1 << target >> diff | 1 << target << diff) & seen) ``` ```python3 [Readable equivalent] class Solution: def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int: # first line in two-liner seen = 1 for row in mat: tmp = 0 for num in set(row): tmp |= seen << num seen = tmp # second line in two-liner bits = 1 << target for diff in count(): if bits & seen: return diff bits |= bits << 1 | bits >> 1 ```
0
0
['Dynamic Programming', 'Bit Manipulation', 'Python3']
0
minimize-the-difference-between-target-and-chosen-elements
Bruteforce
bruteforce-by-tailtit-x80k
Code
tailtit
NORMAL
2024-12-30T19:22:17.684910+00:00
2024-12-30T19:22:17.684910+00:00
6
false
# Code ```python3 [] class Solution: def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int: p_min = sum(min(i) for i in mat) if p_min > target: return p_min - target d = {0} for row in mat: d = {x + i for x in row for i in d if x + i <= (2 * target - p_min)} return min(abs(target - x) for x in d) ```
0
0
['Array', 'Python3']
0
minimize-the-difference-between-target-and-chosen-elements
minimize the difference
minimize-the-difference-by-balaganeshkan-t81u
IntuitionApproachComplexity Time complexity: Space complexity: Code
BALAGANESHKANIKICHARLA
NORMAL
2024-12-21T16:12:28.194994+00:00
2024-12-21T16:12:28.194994+00:00
5
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int minimizeTheDifference(vector<vector<int>>& mat, int target) { int n = mat.size(); int m = mat[0].size(); bitset<5001> dp; dp[0] = 1; for(int i = 0;i < n; i++){ bitset<5001> temp; for(int j = 0;j < m; j++){ temp |= (dp << mat[i][j]); } dp = temp; } int ans = INT_MAX; for(int i=4900;i>=0;i--){ if(dp[i]) ans=min(ans,abs(i-target)); } return ans; } }; ```
0
0
['C++']
0
minimize-the-difference-between-target-and-chosen-elements
Minimize the Difference Between Target and Choosen Element
minimize-the-difference-between-target-a-y7s5
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Naeem_ABD
NORMAL
2024-12-08T10:43:08.795379+00:00
2024-12-08T10:43:08.795419+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```golang []\nfunc minimizeTheDifference(mat [][]int, target int) int {\n\tbaseSummary := 0\n\tmagic := make([][]int, len(mat))\n\tfor ri, rows := range mat {\n\t\tsort.Ints(rows)\n\t\tbaseSummary += rows[0]\n\t\tfor i := 1; i < len(rows); i++ {\n\t\t\tif rows[i] != rows[i-1] {\n\t\t\t\tmagic[ri] = append(magic[ri], rows[i]-rows[0])\n\t\t\t}\n\t\t}\n\t}\n\tminDifference := abs(target - baseSummary)\n\tif baseSummary >= target {\n\t\treturn minDifference\n\t}\n\thash := make(map[int]bool, 871)\n\thash[baseSummary] = true\n\tfor _, tires := range magic {\n\t\tmore := make([]int, 0)\n\t\tfor _, tryValue := range tires {\n\t\t\tfor basic := range hash {\n\t\t\t\tif basic+tryValue > 870 {\n\t\t\t\t\t// iteration order is NOT dependent on any sorted criterion\n\t\t\t\t\t// we should continue, not break\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif hash[basic+tryValue] == false {\n\t\t\t\t\t// we can\'t modify map during iteration\n\t\t\t\t\t// push back to more, insert into map after tires\n\t\t\t\t\tmore = append(more, basic+tryValue)\n\t\t\t\t}\n\t\t\t\tif basic+tryValue == target {\n\t\t\t\t\treturn 0\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor _, mv := range more {\n\t\t\thash[mv] = true\n\t\t}\n\t}\n\tfor k := range hash {\n\t\tif curDifference := abs(target - k); curDifference < minDifference {\n\t\t\tminDifference = curDifference\n\t\t}\n\t}\n\treturn minDifference\n}\n\nfunc abs(v int) int {\n\tif v > 0 {\n\t\treturn v\n\t}\n\treturn v * -1\n}\n```
0
0
['Go']
0
minimize-the-difference-between-target-and-chosen-elements
Python, knapsack dp solution with explanation
python-knapsack-dp-solution-with-explana-quwp
We must select a number from each row to make sum of these number be as close as possible to target, it is similar to knapsack problem.\n\ndp[i][j] is whether w
shun6096tw
NORMAL
2024-11-28T05:47:45.539721+00:00
2024-11-28T05:47:45.539758+00:00
4
false
We must select a number from each row to make sum of these number be as close as possible to ```target```, it is similar to knapsack problem.\n\ndp[i][j] is whether we make ```j``` from row 0 to ```i```.\nmax of ```j``` is target, and when the sum is over target, keep track of it.\n\ndp[i][j] = any(dp[i-1][j - x] for x in each row)\nwe must select a number, so dp[i-1][j] can not be used.\n\nif dp[i-1][j] and j + x > target, we keep track of each minimum of j + x with variable ```gt```. \nBut there have two situations,\none is all number of matrix > target, ```gt``` alway is INF.\nthe other is that found a number j + x at the previous row, we also can add minimum number of row to it.\n```python\ncur_gt = gt + (0 if gt == INF else min(row))\n```\nFinally, check if there is any better answer in range ```(max(2 * target - gt, -1), target]```.\nif ```gt``` is INF, and dp are all False, answer is sum of min of each row - target.\n\ntc is O(m * n * target), sc is O(target).\n\n```python\nINF = 5000\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n dp = [False] * (1 + target)\n dp[0] = True\n gt = INF\n for row in mat:\n cur_gt = gt + (0 if gt == INF else min(row))\n for j in range(target, -1, -1):\n cur = False\n for x in row:\n cur = cur or j - x >= 0 and dp[j - x]\n if dp[j] and j + x > target:\n cur_gt = min(cur_gt, j + x)\n dp[j] = cur\n gt = cur_gt\n \n for i in range(target, max(2 * target - gt, -1), -1):\n if dp[i]:\n return target - i\n return (sum(min(row) for row in mat) if gt == INF else gt) - target\n```
0
0
['Dynamic Programming', 'Python']
0
minimize-the-difference-between-target-and-chosen-elements
scala recursion, memoization, pruning
scala-recursion-memoization-pruning-by-v-aeus
scala []\nobject Solution {\n import scala.util.chaining._\n val mxVal = 70\n val cache = collection.mutable.Map.empty[(Int,Int),Int]\n def minimizeTheDiffe
vititov
NORMAL
2024-11-19T17:42:54.764716+00:00
2024-11-19T17:42:54.764732+00:00
0
false
```scala []\nobject Solution {\n import scala.util.chaining._\n val mxVal = 70\n val cache = collection.mutable.Map.empty[(Int,Int),Int]\n def minimizeTheDifference(_mat: Array[Array[Int]], target: Int): Int = {\n val mat = _mat.map(_.distinct.sorted)\n cache.clear()\n var best = Int.MaxValue\n def f(i: Int, diff: Int): Int = cache.getOrElse((i,diff),{\n if(best < -diff) Int.MaxValue\n //else if(diff - mxVal*i > best) Int.MaxValue\n else if(i<=0) diff.abs.tap(rc => best = best min rc.abs )\n else mat(i-1).iterator.distinct.map(x => f(i-1, diff - x)).min\n }.tap(rc => cache += ((i,diff) -> rc)))\n f(mat.length,target)\n }\n}\n\n```
0
0
['Array', 'Dynamic Programming', 'Matrix', 'Scala']
0
count-valid-paths-in-a-tree
DFS/Tree-DP in C++, Java & Python
dfstree-dp-in-c-java-python-by-cpcs-rdst
Intuition\nLinear sieve to get all the prime numbers that are no larger than n.\nThen do a tree DP (or simply consider it as DFS) to calculate the result.\n\n#
cpcs
NORMAL
2023-09-24T04:01:10.554714+00:00
2023-09-25T03:01:44.541049+00:00
5,225
false
# Intuition\nLinear sieve to get all the prime numbers that are no larger than n.\nThen do a tree DP (or simply consider it as DFS) to calculate the result.\n\n# Approach\nUse linear sieve to get all prime numbers, other sieve algorithms that have higher time complexity are also acceptable.\n\nIn DFS/Tree DP, return 2 values:\n(1) The number of paths from root "goes down" that has no prime numbers, say A.\n(2) The number of paths from root "pass down" that has only one prime numbers, say B.\n\n\n \nIf root is a prime number then:\nroot_A = 0\nroot_B = sigma(A) via all childeren of root.\n\nIf root is not a prime number then:\nroot_A = sigma(A) via all childeren of root.\nroot_B = sigma(B) via all childeren of root.\n\nBefore updating root_A and root_B for each child\nwe add root_A * B + root_B * A to our final answer. That\'s the number of paths "pass through" and has only one prime number. \n\nHere "pass through" means the paths between the root\'s 2 descendants.\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\nC++\n```\nclass Solution {\n long long mul(long long x, long long y) {\n return x * y;\n }\n \n pair<int, int> dfs(int x, int f, const vector<vector<int>> &con, const vector<bool> &prime, long long &r) {\n pair<int, int> v = {!prime[x], prime[x]};\n for (int y : con[x]) {\n if (y == f) continue;\n const auto& p = dfs(y, x, con, prime, r);\n r += mul(p.first, v.second) + mul(p.second, v.first);\n if (prime[x]) {\n v.second += p.first;\n } else {\n v.first += p.first;\n v.second += p.second;\n }\n \n }\n return v;\n }\n \npublic:\n long long countPaths(int n, vector<vector<int>>& edges) {\n vector<bool> prime(n + 1, true);\n prime[1] = false;\n vector<int> all;\n for (int i = 2; i <= n; ++i) {\n if (prime[i]) {\n all.push_back(i);\n }\n for (int x : all) {\n const int temp = i * x;\n if (temp > n) {\n break;\n }\n prime[temp] = false;\n if (i % x == 0) {\n break;\n } \n }\n }\n vector<vector<int>> con(n + 1);\n for (const auto& e : edges) {\n con[e[0]].push_back(e[1]);\n con[e[1]].push_back(e[0]);\n }\n long long r = 0;\n dfs(1, 0, con, prime, r);\n return r;\n \n }\n};\n```\n\nJava\n```\nclass Solution {\n public long countPaths(int n, int[][] edges) {\n List<Boolean> prime = new ArrayList<>(n + 1);\n for (int i = 0; i <= n; ++i) {\n prime.add(true);\n }\n prime.set(1, false);\n \n List<Integer> all = new ArrayList<>();\n for (int i = 2; i <= n; ++i) {\n if (prime.get(i)) {\n all.add(i);\n }\n for (int x : all) {\n int temp = i * x;\n if (temp > n) {\n break;\n }\n prime.set(temp, false);\n if (i % x == 0) {\n break;\n }\n }\n }\n \n List<List<Integer>> con = new ArrayList<>(n + 1);\n for (int i = 0; i <= n; ++i) {\n con.add(new ArrayList<>());\n }\n for (int[] e : edges) {\n con.get(e[0]).add(e[1]);\n con.get(e[1]).add(e[0]);\n }\n \n long[] r = {0};\n dfs(1, 0, con, prime, r);\n return r[0];\n }\n \n private long mul(long x, long y) {\n return x * y;\n }\n \n private class Pair {\n int first;\n int second;\n \n Pair(int first, int second) {\n this.first = first;\n this.second = second;\n }\n }\n \n private Pair dfs(int x, int f, List<List<Integer>> con, List<Boolean> prime, long[] r) {\n Pair v = new Pair(!prime.get(x) ? 1 : 0, prime.get(x) ? 1 : 0);\n for (int y : con.get(x)) {\n if (y == f) continue;\n Pair p = dfs(y, x, con, prime, r);\n r[0] += mul(p.first, v.second) + mul(p.second, v.first);\n if (prime.get(x)) {\n v.second += p.first;\n } else {\n v.first += p.first;\n v.second += p.second;\n }\n }\n return v;\n }\n}\n```\nPython\n```\nclass Solution:\n def countPaths(self, n: int, edges: List[List[int]]) -> int:\n def mul(x, y):\n return x * y\n \n def dfs(x, f, con, prime, r):\n v = [1 - prime[x], prime[x]]\n for y in con[x]:\n if y == f:\n continue\n p = dfs(y, x, con, prime, r)\n r[0] += mul(p[0], v[1]) + mul(p[1], v[0])\n if prime[x]:\n v[1] += p[0]\n else:\n v[0] += p[0]\n v[1] += p[1]\n return v\n \n prime = [True] * (n + 1)\n prime[1] = False\n \n all_primes = []\n for i in range(2, n + 1):\n if prime[i]:\n all_primes.append(i)\n for x in all_primes:\n temp = i * x\n if temp > n:\n break\n prime[temp] = False\n if i % x == 0:\n break\n \n con = [[] for _ in range(n + 1)]\n for e in edges:\n con[e[0]].append(e[1])\n con[e[1]].append(e[0])\n \n r = [0]\n dfs(1, 0, con, prime, r)\n return r[0]\n\n```\n
41
3
['Dynamic Programming', 'C++', 'Java', 'Python3']
10
count-valid-paths-in-a-tree
[Python3] DSU
python3-dsu-by-awice-r3ss
Union all the composite nodes, now we just have to count from a bipartite tree.\n\nThis is easy, as all the path lengths are at most 3.\n\n# Code\n\nMX = 100001
awice
NORMAL
2023-09-24T04:02:05.304359+00:00
2023-09-24T04:02:05.304387+00:00
1,511
false
Union all the composite nodes, now we just have to count from a bipartite tree.\n\nThis is easy, as all the path lengths are at most 3.\n\n# Code\n```\nMX = 100001\nlpf = [0] * MX\nfor i in range(2, MX):\n if lpf[i] == 0:\n for j in range(i, MX, i):\n lpf[j] = i\n\nclass DSU:\n def __init__(self, N):\n self.par = list(range(N))\n self.sz = [1] * N\n\n def find(self, x):\n if self.par[x] != x:\n self.par[x] = self.find(self.par[x])\n return self.par[x]\n\n def union(self, x, y):\n xr, yr = self.find(x), self.find(y)\n if xr == yr:\n return False\n if self.sz[xr] < self.sz[yr]:\n xr, yr = yr, xr\n self.par[yr] = xr\n self.sz[xr] += self.sz[yr]\n return True\n\n def size(self, x):\n return self.sz[self.find(x)]\n\nclass Solution:\n def countPaths(self, n: int, edges: List[List[int]]) -> int:\n # Union composite nodes\n dsu = DSU(n + 1)\n for u, v in edges:\n if lpf[u] != u and lpf[v] != v:\n dsu.union(u, v)\n \n count = [1] * (n + 1) # total size of neighbors counted\n ans = 0\n for u, v in edges:\n if (lpf[u] == u) ^ (lpf[v] == v):\n if lpf[u] != u:\n u, v = v, u\n # u is a prime node, v is a composite node\n ans += count[u] * dsu.size(v)\n count[u] += dsu.size(v)\n return ans\n```
30
0
['Python3']
6