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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
maximum-difference-score-in-a-grid | [Python] Simple DP without math, O(MN) | python-simple-dp-without-math-omn-by-arv-zkf1 | Key Ideas\n- Fill DP array up from bottom right to top left.\n- When we iterate over cell (i, j), we compute the highest scoring path starting from (i, j) with | arvganesh | NORMAL | 2024-05-12T16:51:59.762620+00:00 | 2024-05-12T16:53:40.162415+00:00 | 63 | false | ### Key Ideas\n- Fill DP array up from bottom right to top left.\n- When we iterate over cell `(i, j)`, we compute the highest scoring path starting from `(i, j)` with **at least 1 move**.\n- The requirement of paths being at least 1 move long make this problem tricky.\n\nIgnoring any bounds checks, the recurrence + calculation of the answer looks like this:\n\nAt this step,\n\n`dp[i][j] = maximum score starting from cell (i, j)`\n\n`dp[i][j] = max(dp[i][j + 1], dp[i + 1][j]) - grid[i][j]`\n\nThe term "`max(dp[i][j + 1], dp[i + 1][j])`" represents the maximum score in the black rectangle. We can compute that maximum using the scores from the blue and red rectangles. Since we are building the DP array from bottom right to top left, when we compute `dp[i][j]`, we will already know `dp[i + 1][j]` (red) and `dp[i][j + 1]` (blue). \n<img src="https://assets.leetcode.com/users/images/8bb6a9ba-26a7-4654-818d-c59a9e795526_1715530756.027575.png" width="500"/>\n\nNow, we can update our answer: `answer = max(dp[i][j], answer)`.\n\nCurrently, `dp[i][j]` is the max score for all paths starting from cell `(i, j)` and making at least 1 more move. In the future, when we reuse this result when computing the answer for another starting cell, we might not consider paths that end with cell `(i, j)`. \n\nThat\'s why we need this line:\n\n`dp[i][j] = max(dp[i][j], 0) + grid[i][j]`\n\nThe trick here is interspersing updating `answer` with computing `dp[i][j]` so we consider all paths with at least 1 move.\n\n```\ndef maxScore(self, grid: List[List[int]]) -> int: \n N, M = len(grid), len(grid[0])\n dp = [[-10**9] * M for _ in range(N)]\n answer = -10**9\n for i in range(N - 1, -1, -1):\n for j in range(M - 1, -1, -1):\n if j + 1 < M:\n dp[i][j] = max(dp[i][j], dp[i][j + 1] - grid[i][j])\n \n if i + 1 < N:\n dp[i][j] = max(dp[i][j], dp[i + 1][j] - grid[i][j])\n \n answer = max(dp[i][j], answer)\n dp[i][j] = max(dp[i][j], 0) + grid[i][j]\n \n return answer\n``` | 2 | 0 | ['Python'] | 0 |
maximum-difference-score-in-a-grid | C++ | Basic DP approach | Tabulation | c-basic-dp-approach-tabulation-by-mitali-ozk0 | Intuition\nMy intuition was that the problem can be solved using DP since to calculate cost at each cell we will require the previous moves costs.\n\nIf the mov | mitalidxt | NORMAL | 2024-05-12T15:48:31.774915+00:00 | 2024-05-12T15:48:31.774935+00:00 | 144 | false | # Intuition\nMy intuition was that the problem can be solved using DP since to calculate cost at each cell we will require the previous moves costs.\n\nIf the move can start and end at any cell, I created a 2D dp matrix where each cell represented the maximum cost that can be achieved if it was the destination cell. \n\nTo calculate cost at each cell , there are two possibilities - either its a new move or its the last move of a series of moves. So we take the maximum of them. Since there are two moves - right and bottom, so the costs at each dp cell depends upon its left and top neighbour. \n \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\nHere\u2019s how the costs are calculated:\n\n##### For the first row (only right moves): \n- The cost of each cell is calculated as the maximum of two values:\nThe cost to move from j-1 to j, which is grid[i][j]-grid[i][j-1]\nThe maximum cost till grid[i][j-1] plus the cost to move from j-1 to j, which is dp[i][j-1]+grid[i][j]-grid[i][j-1]\n##### For the first column (only down moves): \n- The cost of each cell is calculated as the maximum of two values:\nThe cost to move from i-1 to i, which is grid[i][j]-grid[i-1][j]\nThe maximum cost till grid[i-1][j] plus the cost to move from i-1 to i, which is dp[i-1][j]+grid[i][j]-grid[i-1][j]\n##### For the remaining cells (bottom and right moves): \n- The cost of each cell is calculated as follows:\nIf it is a continued move, the cost is c1 = max(dp[i][j-1]+grid[i][j]-grid[i][j-1], dp[i-1][j]+grid[i][j]-grid[i-1][j])\nIf it is a new move, the cost is c2 = max(grid[i][j]-grid[i][j-1], grid[i][j]-grid[i-1][j])\nThe final cost for the cell is dp[i][j] = max(c1, c2)\n\nFinally, the maximum element in the DP matrix is returned (other than the first element because we need at least one move) \n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(m*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(m*n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n //create a dp array of size m*n\n vector<vector<int>> dp(m, vector<int>(n, 0));\n dp[0][0]=0;\n int c1,c2;\n int res=INT_MIN;\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(i==0 && j==0){\n continue;\n }\n if(i==0){\n dp[i][j]=max(grid[i][j]-grid[i][j-1],grid[i][j]-grid[i][j-1]+dp[i][j-1]);\n res=max(res,dp[i][j]);\n }\n else if(j==0){\n dp[i][j]=max(grid[i][j]-grid[i-1][j],grid[i][j]-grid[i-1][j]+dp[i-1][j]);\n res=max(res,dp[i][j]);\n }\n else{\n c1=max(dp[i][j-1]+grid[i][j]-grid[i][j-1],dp[i-1][j]+grid[i][j]-grid[i-1][j]);\n c2=max(grid[i][j]-grid[i][j-1],grid[i][j]-grid[i-1][j]);\n dp[i][j]=max(c1,c2); \n res=max(res,dp[i][j]); \n }\n\n\n }\n \n }\n return res;\n }\n \n};\n``` | 2 | 0 | ['Dynamic Programming', 'C++'] | 0 |
maximum-difference-score-in-a-grid | Easy DP | Memoization | Trying all below and right cells | Solution in c++ | easy-dp-memoization-trying-all-below-and-9ejc | Intuition\nAs you can see option that you can move at any right cell or below cell and to try all possible ways use Dynamic Programming.\n\n# Approach\nThe key | shekhar125 | NORMAL | 2024-05-12T07:16:00.170784+00:00 | 2024-05-12T07:16:00.170818+00:00 | 312 | false | # Intuition\nAs you can see option that you can move at any right cell or below cell and to try all possible ways use Dynamic Programming.\n\n# Approach\nThe key part is to understand that in you main function you are trying for all below cells and right cells but only you consider further values from function that right and below cell if it\'s positive.As below code is telling that you do move to below cell but consider that cell value as t only if it\'s positive because then it will make sense to take it other do one move and stop as we want to do atleast one move.Same you can do for all right cells.\n\n```\nint t=f(r,j,g);\nif(t>0)\n ans=max(ans,-g[i][j]+g[r][j]+t);\n else\n ans=max(ans,-g[i][j]+g[r][j]);\n```\n\n\n\nAnother point it that the right most and bottom most cell will not be choosen as starting point because you can make any move starting from this cell.That\'s why in below code I have neglected that cell as starting point.\n\n for(int i=0;i<m;++i)\n {\n for(int j=0;j<n;++j)\n {\n if(!(i==m-1 && j==n-1))\n {\n maxi=max(maxi,f(i,j,g)); \n }\n \n }\n }\n\n\nNow understand base condition that why when someone reaches i==m-1 and j==n-1 you have to return 0 because no further value can be gained and every cell can be reachable to that last cell by doing some moves.\n\nNow time complexity is actually $$O(n*m)$$ beacause let\'s say you call first cell i==0 and j==0 so it will call all the function it\'s right side and down which will be get memoized by dp array so further when I will call that cell as starting point it will return from dp array you can tell time complexity as $$O(2*n*m)$$\n# Complexity\n- Time complexity:\n$$O(2*n*m)$$\n\n- Space complexity:\n$$O(n*m)$$ \n\n# Code\n```\nint dp[1001][1001];\n\nint f(int i,int j,vector<vector<int>>& g)\n{\n if(dp[i][j]!=-1) return dp[i][j];\n int m=g.size();\n int n=g[0].size();\n if(i==m-1 && j==n-1) return dp[i][j]=0;\n int ans=-1e9;\n for(int r=i+1;r<m;++r)\n {\n int t=f(r,j,g);\n if(t>0)\n ans=max(ans,-g[i][j]+g[r][j]+t);\n else\n ans=max(ans,-g[i][j]+g[r][j]);\n \n }\n for(int c=j+1;c<n;++c)\n {\n int t=f(i,c,g);\n if(t>0)\n ans=max(ans,-g[i][j]+g[i][c]+t);\n else\n ans=max(ans,-g[i][j]+g[i][c]);\n }\n \n return dp[i][j]=ans;\n}\n\n\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& g) {\n memset(dp,-1,sizeof(dp));\n int m=g.size();\n int n=g[0].size();\n int maxi=-1e9;\n for(int i=0;i<m;++i)\n {\n for(int j=0;j<n;++j)\n {\n if(!(i==m-1 && j==n-1))\n {\n maxi=max(maxi,f(i,j,g)); \n }\n \n }\n }\n \n return maxi;\n }\n};\n``` | 2 | 0 | ['Dynamic Programming', 'Memoization', 'Matrix', 'C++'] | 2 |
maximum-difference-score-in-a-grid | ✅Accepted Java Code || O(n^2) | accepted-java-code-on2-by-thilaknv-izlx | Complexity\n- Time complexity : O(n^2)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity : O(n^2)\n Add your space complexity here, e.g. O(n) \n | thilaknv | NORMAL | 2024-05-12T04:59:34.249011+00:00 | 2024-05-12T04:59:34.249031+00:00 | 15 | false | # Complexity\n- Time complexity : $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity : $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int maxScore(List<List<Integer>> grid) {\n int res = 0;\n \n \n int n = grid.size();\n int m = grid.get(0).size();\n int[][] A = new int[n][m];\n \n for(int i = 0; i < n; i++){\n List<Integer> arr = grid.get(i);\n for(int j = 0; j < m; j++)\n A[i][j] = arr.get(j);\n }\n \n int[][] dp = new int[n][m];\n // dp[0] = \n \n int result = Integer.MIN_VALUE;\n for(int j = 1; j < m; j++){\n dp[0][j] = Math.max(0, dp[0][j - 1]);\n dp[0][j] -= A[0][j - 1];\n dp[0][j] += A[0][j];\n if(result < dp[0][j])\n result = dp[0][j];\n }\n for(int i = 1; i < n; i++){\n dp[i][0] = Math.max(0, dp[i - 1][0]);\n dp[i][0] -= A[i - 1][0];\n dp[i][0] += A[i][0];\n if(result < dp[i][0])\n result = dp[i][0];\n }\n \n for(int i = 1; i < n; i++){\n for(int j = 1; j < m; j++){\n int num1 = Math.max(0, dp[i][j - 1]);\n num1 -= A[i][j - 1];\n int num2 = Math.max(0, dp[i - 1][j]);\n num2 -= A[i - 1][j];\n \n dp[i][j] = Math.max(num1, num2) + A[i][j];\n if(result < dp[i][j])\n result = dp[i][j];\n }\n }\n \n return result;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
maximum-difference-score-in-a-grid | Easy to understand Step by Step Solution | C++ | DP | easy-to-understand-step-by-step-solution-tcjk | Intuition\n Describe your first thoughts on how to solve this problem. \nDynamic Programming to reduce repetation in code flow.\n\n# Approach\n Describe your ap | yashugshejwal | NORMAL | 2024-05-12T04:45:42.584555+00:00 | 2024-05-12T04:45:42.584575+00:00 | 378 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDynamic Programming to reduce repetation in code flow.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSolve the problem by storing maximum possible score at each square in grid, starting from the bottom-rightmost square.\nI manually initialised the dp to get clearer idea of the code flow.\n\n# Complexity\n- Time complexity: $$O(m*n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m*n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n vector<vector<int>> dp( m , vector<int> (n)); \n // corner\n dp[m-1][n-1] = INT_MIN;\n // last row\n int addR, valR, addB, valB, ans = INT_MIN;\n for (int i = n-2; i >= 0; i--) {\n valR = grid[m-1][i+1] - grid[m-1][i];\n if (dp[m-1][i+1] != INT_MIN) addR = dp[m-1][i+1] + valR;\n else addR = valR;\n dp[m-1][i] = max(valR, addR);\n ans = max(ans, dp[m-1][i]);\n }\n // last column\n for (int i = m-2; i >= 0; i--) {\n valB = grid[i+1][n-1] - grid[i][n-1];\n if (dp[i+1][n-1] != INT_MIN) addB = dp[i+1][n-1] + valB;\n else addB = valB;\n dp[i][n-1] = max(valB, addB);\n ans = max(ans, dp[i][n-1]);\n }\n // others\n int Rmax, Bmax;\n for (int i = m-2; i >= 0; i--) {\n for (int j = n-2; j >= 0; j--) {\n valR = grid[i][j+1] - grid[i][j];\n if (dp[i][j+1] != INT_MIN) addR = dp[i][j+1] + valR;\n else addR = valR;\n Rmax = max(valR, addR);\n \n valB = grid[i+1][j] - grid[i][j];\n if (dp[i+1][j] != INT_MIN) addB = dp[i+1][j] + valB;\n else addB = valB;\n Bmax = max(valB, addB);\n \n dp[i][j] = max(Rmax, Bmax);\n ans = max(ans, dp[i][j]);\n }\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['Dynamic Programming', 'C++'] | 3 |
maximum-difference-score-in-a-grid | Java DP matrix | java-dp-matrix-by-deleted_user-40sq | Intuition\nThe approach is to utilize dynamic programming to compute the maximum score that can be achieved by reaching each cell of the grid.\n# Approach\nInit | deleted_user | NORMAL | 2024-05-12T04:41:32.261995+00:00 | 2024-05-12T04:41:32.262014+00:00 | 107 | false | # Intuition\nThe approach is to utilize dynamic programming to compute the maximum score that can be achieved by reaching each cell of the grid.\n# Approach\nInitialize a 2D array dp to store the maximum score that can be achieved at each cell.\nStart from the bottom-right corner of the grid and iteratively fill the dp array by considering the maximum score achievable by moving either downward or rightward from the current cell, or by choosing the current cell itself.\nAfter filling the dp array, iterate through each cell again to find the maximum difference between the current cell\'s value and the maximum score achievable from adjacent cells. This represents the maximum score that can be gained by choosing the current cell and then moving forward.\nReturn the maximum score found.\n# Complexity\n- Time complexity:\nO(m * n)\n- Space complexity:\nO(m * n)\n# Code\n```\nimport java.util.*;\n\nclass Solution {\n public int maxScore(List<List<Integer>> grid) {\n int m = grid.size();\n int n = grid.get(0).size();\n \n int[][] dp = new int[m][n];\n for (int[] row : dp) {\n Arrays.fill(row, Integer.MIN_VALUE);\n }\n \n dp[m - 1][n - 1] = grid.get(m - 1).get(n - 1);\n \n for (int i = m - 1; i >= 0; --i) {\n for (int j = n - 1; j >= 0; --j) {\n if (i < m - 1)\n dp[i][j] = Math.max(dp[i][j], dp[i + 1][j]);\n if (j < n - 1)\n dp[i][j] = Math.max(dp[i][j], dp[i][j + 1]);\n dp[i][j] = Math.max(dp[i][j], grid.get(i).get(j));\n }\n }\n \n int Max = Integer.MIN_VALUE;\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (i < m - 1)\n Max = Math.max(Max, dp[i + 1][j] - grid.get(i).get(j));\n if (j < n - 1)\n Max = Math.max(Max, dp[i][j + 1] - grid.get(i).get(j));\n \n }\n }\n return Max;\n }\n}\n\n``` | 2 | 0 | ['Java'] | 1 |
maximum-difference-score-in-a-grid | 😎Simplest CPP implementation....just DP things✅ | simplest-cpp-implementationjust-dp-thing-9gf7 | Intuition\n Describe your first thoughts on how to solve this problem. \nWe will be starting from the bottom right element, becoz we know that for that element | Engg_Ayush | NORMAL | 2024-05-12T04:15:16.536053+00:00 | 2024-05-12T04:15:16.536088+00:00 | 240 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe will be starting from the bottom right element, becoz we know that for that element the value is 0.\n\nand than the simple traversal and from the bottom right to top left element and some calculation.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Create 2d dp array , and than assign 0 to the last element(dp[row-1][col-1]=0).\n- now for every element in the array we will calculate the maxRowSum and maxColSum .\n- maxRowSum : this will be the sumation which will be calculated so that to find the max value in the row in which element is present.\n- maxColSum: this will be the sumation which will be calculated so that to find the max value in the column in which element is present.\n- than we will take the max of both ans return the answer.\n\n\n# Complexity\n- Time complexity: O(n*m)*O(n+m) : where n & m are size of row and column\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n*m) : where n & m are size of row and column\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& arr) {\n \n int row=arr.size(), col=arr[0].size(), ans=INT_MIN;\n \n vector<vector<int>> dp(row, vector<int>(col, 0));\n dp[row-1][col-1] = 0;\n \n \n for(int i=row-1; i>=0; i--){\n for(int j=col-1; j>=0; j--){\n \n if(i==row-1 && j==col-1)continue;\n \n int val = arr[i][j];\n \n //calculate row sum\n int maxRowSum = INT_MIN;\n for(int c=j+1; c<col; c++){\n int rowSum = (arr[i][c]-val) + dp[i][c];\n maxRowSum = max(maxRowSum, max(rowSum, (arr[i][c]-val)));\n }\n \n //calculate column sum\n int maxColSum = INT_MIN;\n for(int r=i+1; r<row; r++){\n int colSum = (arr[r][j]-val) + dp[r][j];\n maxColSum = max(maxColSum, max(colSum, (arr[r][j]-val)));\n }\n \n // cout<<arr[i][j]<<" "<<maxColSum<<" "<<maxRowSum<<endl;\n \n dp[i][j]=max(maxRowSum, maxColSum);\n \n ans=max(ans, max(maxRowSum, maxColSum));\n }\n \n }\n \n return ans;\n \n }\n};\n``` | 2 | 2 | ['Array', 'Dynamic Programming', 'Python', 'C++', 'Java', 'Python3', 'C#'] | 2 |
maximum-difference-score-in-a-grid | DP || JAVA || Memoization | dp-java-memoization-by-pavan_d_naik-o933 | Complexity\n- Time complexity: O(mn)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(mn)\n Add your space complexity here, e.g. O(n) \n\n# | PAVAN_D_NAIK | NORMAL | 2024-05-12T04:05:22.312310+00:00 | 2024-05-12T04:05:22.312344+00:00 | 363 | false | # Complexity\n- Time complexity: $$O(m*n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m*n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n int[][] dp;\n int m,n;\n int min=-(int)1e7;\n int max=min;\n private int helper(int i,int j,List<List<Integer>> g){\n if(i>=m || j>=n)return min;\n if(dp[i][j]!=min)return dp[i][j];\n\n int v = g.get(i).get(j);\n\n int ml1=min;\n int ml2=min;\n if(i!=m-1)ml1 =g.get(i+1).get(j)-v+ Math.max(0,helper(i+1,j,g));\n if(j!=n-1)ml2 =g.get(i).get(j+1)-v+ Math.max(0,helper(i,j+1,g));\n int ml = Math.max(ml1,ml2);\n dp[i][j] = ml;\n max = Math.max(max,dp[i][j]);\n return dp[i][j];\n }\n \n public int maxScore(List<List<Integer>> g) {\n m = g.size();\n n = g.get(0).size();\n dp = new int[m][n];\n for(int i=0;i<m;i++){\n Arrays.fill(dp[i],min);\n }\n helper(0,0,g);\n return max;\n }\n}\n``` | 2 | 0 | ['Dynamic Programming', 'Memoization', 'Java'] | 2 |
maximum-difference-score-in-a-grid | ✅ Java Solution | java-solution-by-harsh__005-06yv | CODE\nJava []\npublic int maxScore(List<List<Integer>> grid) {\n\tint r = grid.size(), c = grid.get(0).size();\n\tint res = Integer.MIN_VALUE;\n\n\tint[][] arr | Harsh__005 | NORMAL | 2024-05-12T04:02:32.790643+00:00 | 2024-05-12T04:02:32.790667+00:00 | 386 | false | ## **CODE**\n```Java []\npublic int maxScore(List<List<Integer>> grid) {\n\tint r = grid.size(), c = grid.get(0).size();\n\tint res = Integer.MIN_VALUE;\n\n\tint[][] arr = new int[r][c];\n\tfor(int i=r-1; i>=0; i--) {\n\t\tint max = grid.get(i).get(c-1);\n\t\tarr[i][c-1] = max;\n\t\tfor(int j=c-2; j>=0; j--) {\n\t\t\tint val = grid.get(i).get(j);\n\n\t\t\tint diff = max-val;\n\t\t\tres = Math.max(res, diff);\n\t\t\tmax = Math.max(max, val);\n\n\t\t\tarr[i][j] = diff;\n\t\t}\n\t}\n\n\tfor(int j=c-1; j>=0; j--) {\n\t\tint val = grid.get(r-1).get(j);\n\t\tint max = val;\n\t\tif(j < c-1 && arr[r-1][j]>0) max = val+arr[r-1][j];\n\n\t\tfor(int i=r-2; i>=0; i--){\n\t\t\tval = grid.get(i).get(j);\n\n\t\t\tint diff = max-val;\n\t\t\tres = Math.max(res, diff);\n\n\t\t\tif(j < c-1 && arr[i][j]>0) val+=arr[i][j];\n\t\t\tmax = Math.max(max, val);\n\t\t}\n\t}\n\n\treturn res;\n}\n``` | 2 | 0 | ['Java'] | 1 |
maximum-difference-score-in-a-grid | Rectangle approach O(m*n) | rectangle-approach-omn-by-tq9iyziust-kiik | Intuition\nThe largest jump with cell (a,b) is to find the smallest value of rectangle (0,0) -> (a,b) except the point at (a,b)\n Describe your first thoughts o | tunt6 | NORMAL | 2024-11-15T07:53:02.419788+00:00 | 2024-11-15T07:53:02.419850+00:00 | 8 | false | # Intuition\nThe largest jump with cell (a,b) is to find the smallest value of rectangle (0,0) -> (a,b) except the point at (a,b)\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n- Create an O(n) array that stores the smallest value before reaching cell (x,y) of row x.\n\n- When browsing to position (x,b), the smallest value for this cell will be = the smallest value of the left cell (x, b-1) and grid(x,b-1) compared to the smallest value of the cell above (x-1,b) and grid(x-1, b)\n\n- After finding the smallest value in the rectangle (0,0) -> (x,y), take the value of the cell grid(x,y) minus it, it will give the largest jump whose end point is cell (x,y) called step(x,y). At this time, we update the result res = min(res, step(x,y))\n\n- Finally return res\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(m*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int maxScore(List<List<Integer>> grid) {\n int res = Integer.MIN_VALUE;\n int[] t = new int[grid.get(0).size()];\n for (int i = 0; i < grid.size(); i++) {\n for (int j = 0; j < grid.get(0).size(); j++) {\n if (i == 0) {\n if (j == 0) {\n t[j] = Integer.MAX_VALUE;\n } else {\n t[j] = Math.min(t[j-1], grid.get(i).get(j-1));\n }\n } else {\n if (j == 0) {\n t[j] = Math.min(t[j], grid.get(i-1).get(j));\n } else {\n t[j] = Math.min(Math.min(t[j], grid.get(i-1).get(j)), Math.min(t[j-1], grid.get(i).get(j-1)));\n }\n }\n res = Math.max(res, grid.get(i).get(j) - t[j]);\n }\n }\n return res;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
maximum-difference-score-in-a-grid | c++ solution | c-solution-by-dilipsuthar60-a74r | \nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int n=grid.size();\n int m=grid[0].size();\n int ans=-1e8;\n | dilipsuthar17 | NORMAL | 2024-10-27T12:22:36.554159+00:00 | 2024-10-27T12:22:36.554192+00:00 | 2 | false | ```\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int n=grid.size();\n int m=grid[0].size();\n int ans=-1e8;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n int prevMin=1e9;\n if(i==0&&j==0) continue;\n if(i>0) prevMin=min(prevMin,grid[i-1][j]);\n if(j>0) prevMin=min(prevMin,grid[i][j-1]);\n ans=max(ans,grid[i][j]-prevMin);\n grid[i][j]=min(grid[i][j],prevMin);\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C', 'C++'] | 0 |
maximum-difference-score-in-a-grid | Smallest and Easiest one (Beats 100% of Users) | smallest-and-easiest-one-beats-100-of-us-2gl0 | 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 | cookie_33 | NORMAL | 2024-07-30T04:52:24.935087+00:00 | 2024-07-30T04:52:24.935105+00:00 | 94 | 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: O(N*M)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& v) {\n int n=v.size(),m=v[0].size();\n int ans=INT_MIN,c;\n for(int i=n-1;i>=0;i--){\n for(int j=m-1;j>=0;j--)\n {\n c=INT_MIN;\n if(i+1<n) c=v[i+1][j];\n if(j+1<m) c=max(c,v[i][j+1]);\n if(c!=INT_MIN) ans=max(ans,c-v[i][j]);\n v[i][j]=max(v[i][j],c);\n }\n }\n return ans;\n }\n};\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n``` | 1 | 0 | ['Dynamic Programming'] | 0 |
maximum-difference-score-in-a-grid | DP Solution | Easy Approach | O(n^2) | Space Optimised | dp-solution-easy-approach-on2-space-opti-aw5d | Intuition\nIt can be observed that for every index except last one, we have two options to traverse: Rightwards and Downwards. We can avoid many computations by | HariBhakt | NORMAL | 2024-05-28T18:44:04.197500+00:00 | 2024-05-28T18:44:04.197520+00:00 | 36 | false | # Intuition\nIt can be observed that for every index except last one, we have two options to traverse: Rightwards and Downwards. We can avoid many computations by traversing bottom-right to top-left.\n\nDry Run:\n------------\n \nArray: \n\n[[ 9 5 7 3 ],\n[ 8 9 6 1 ],\n[ 6 7 14 3 ],\n[ 2 5 3 1 ]]\n\nDP Array:\n\n[[ 5 9 7 0 ],\n[ 6 5 8 2 ],\n[ 8 7 -11 -2 ],\n[ 3 -2 -2 -1e5 ]]\n\n# Approach\nTraverse from bottom right to top-left and try to store maxValue in DP.\n\n# Complexity\n- Time complexity: $$O(n*m)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int n = grid.size(), m = grid[0].size();\n vector<vector<int>> dp(n, vector<int>(m, -1e5));\n\n // Last Option is not valid , so it is set as -1e5.\n int maxAns = INT_MIN;\n // Fill dp for the bottom row (except the last cell)\n for (int j = m - 2; j >= 0; j--) {\n dp[n - 1][j] =\n max(grid[n - 1][j + 1] - grid[n - 1][j] + dp[n - 1][j + 1],\n grid[n - 1][j + 1] - grid[n - 1][j]);\n maxAns = max(maxAns, dp[n - 1][j]);\n }\n\n // Fill dp for the right column (except the last cell)\n for (int i = n - 2; i >= 0; i--) {\n dp[i][m - 1] =\n max(grid[i + 1][m - 1] - grid[i][m - 1] + dp[i + 1][m - 1],\n grid[i + 1][m - 1] - grid[i][m - 1]);\n maxAns = max(maxAns, dp[i][m - 1]);\n }\n\n // Fill dp for the rest of the grid (bottom to top, right to left)\n for (int i = n - 2; i >= 0; i--) {\n for (int j = m - 2; j >= 0; j--) {\n dp[i][j] = max(max(grid[i][j + 1] - grid[i][j] + dp[i][j + 1],\n grid[i][j + 1] - grid[i][j]),\n max(grid[i + 1][j] - grid[i][j] + dp[i + 1][j],\n grid[i + 1][j] - grid[i][j]));\n maxAns = max(maxAns, dp[i][j]);\n }\n }\n\n return maxAns;\n }\n};\n\n```\n\n## Space Optimised Code\n```\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int n = grid.size(), m = grid[0].size();\n vector<int> dp(m, -1e5); \n int maxAns = INT_MIN;\n // Fill dp for the bottom row (except the last cell)\n for (int j = m - 2; j >= 0; j--) {\n dp[j] = max(grid[n - 1][j + 1] - grid[n - 1][j] + dp[j + 1],\n grid[n - 1][j + 1] - grid[n - 1][j]);\n maxAns = max(maxAns, dp[j]);\n }\n\n // Temporary vector to store the previous row\'s dp values\n vector<int> prev_dp = dp;\n\n // Fill dp for the rest of the grid (bottom to top, right to left)\n for (int i = n - 2; i >= 0; i--) {\n dp[m - 1] = max(grid[i + 1][m - 1] - grid[i][m - 1] + prev_dp[m - 1],\n grid[i + 1][m - 1] - grid[i][m - 1]);\n maxAns = max(maxAns, dp[m - 1]);\n for (int j = m - 2; j >= 0; j--) {\n dp[j] = max(max(grid[i][j + 1] - grid[i][j] + dp[j + 1],\n grid[i][j + 1] - grid[i][j]),\n max(grid[i + 1][j] - grid[i][j] + prev_dp[j],\n grid[i + 1][j] - grid[i][j]));\n maxAns = max(maxAns, dp[j]);\n }\n prev_dp = dp;\n }\n\n return maxAns;\n }\n};\n```\n | 1 | 0 | ['C++'] | 0 |
maximum-difference-score-in-a-grid | 4 Solutions | 3D-DP, 2D-DP | 4-solutions-3d-dp-2d-dp-by-shahsb-8n3r | Solution 1 to 3 (3D-DP Recursion->memoization->tabulation):\n Idea is simple - Simulate taking & not taking behavior at each cell.\n\n# Solution-4: (2D-DP):\n A | shahsb | NORMAL | 2024-05-18T07:06:17.610859+00:00 | 2024-05-18T07:06:17.610893+00:00 | 24 | false | # Solution 1 to 3 (3D-DP Recursion->memoization->tabulation):\n* Idea is simple - Simulate taking & not taking behavior at each cell.\n\n# Solution-4: (2D-DP):\n* At each cell, you should be able to figure out the smallest possible number till that point (i.e from it\'s left and top side).\n* Consider the current cell as the max item and take diff. Track the result on the way (i.e max diff possible).\n# CODE:\n```\nclass Solution {\n unordered_map<string, int> dp;\n vector<vector<int>> grid;\n vector<vector<vector<int>>> dp1;\npublic:\n int maxScore(vector<vector<int>>& g) \n {\n grid = g;\n int ans = INT_MIN;\n if ( isStrictlyIncreasing(grid, ans) )\n return ans;\n \n // SOL-1: RECURSION -- TLE -- 505 / 564 test cases passed. -- 89.53%\n // return dfs(grid, 0, 0, -1);\n \n // SOL-2: MEMOIZATION -- TLE -- 505 / 564 test cases passed. -- 89.53%\n // return memo(0, 0, -1);\n \n // SOL-3: OPtimized Memo -- TLE -- 505 / 564 test cases passed. -- 89.53%\n // dp1 = vector<vector<vector<int>>>(grid.size()+1, vector<vector<int>>(grid[0].size()+1, vector<int>(1e5+1, -1)));\n // return memo1(0,0,-1);\n \n // SOL-4: 2D DP -- TC: O(m*n), SC: O(1) -- 100% -- All TCs passed.\n return sol4(g);\n }\n \n\t// SOL-4: 2D DP -- TC: O(m*n), SC: O(1) -- 100% -- All TCs passed.\n int sol4(vector<vector<int>>& grid)\n {\n int m = grid.size();\n int n = grid[0].size();\n int ans = INT_MIN;\n \n for ( int i=0; i<m; i++ )\n {\n for ( int j=0; j<n; j++ )\n {\n int mn = INT_MAX;\n if ( i==0 && j==0 ) continue;\n // top\n if (i) mn = min(mn, grid[i-1][j]);\n\n // left\n if (j) mn = min(mn, grid[i][j-1]);\n ans = max(ans, grid[i][j] - mn);\n grid[i][j] = min(grid[i][j], mn);\n }\n }\n return ans;\n }\n \n // SOL-3: OPTIMIZED MEMO -- TLE -- 505 / 564 test cases passed. -- 89.53%\n int memo1(int i, int j, int prev)\n {\n if ( i>=grid.size() || j>=grid[0].size() )\n return 0;\n \n if ( dp1[i][j][prev+1] != -1 )\n return dp1[i][j][prev+1];\n \n // take\n int ans1 = -1;\n if ( prev == -1 )\n ans1 = max(memo(i+1, j, grid[i][j]), memo(i, j+1, grid[i][j]));\n else\n ans1 = grid[i][j] - prev + max(memo(i+1, j, grid[i][j]), memo(i, j+1, grid[i][j]));\n \n // do not take\n int ans2 = max(memo(i+1, j, prev), memo(i, j+1, prev));\n return dp1[i][j][prev+1] = max(ans1, ans2);\n }\n \n // SOL-2: MEMOIZATION -- TLE -- 505 / 564 test cases passed. -- 89.53%\n int memo(int i, int j, int prev)\n {\n if ( i>=grid.size() || j>=grid[0].size() )\n return 0;\n \n string key = to_string(i) + "_" + to_string(j) + "_" + to_string(prev);\n if ( dp.find(key) != dp.end() )\n return dp[key];\n \n // take\n int ans1 = -1;\n if ( prev == -1 )\n ans1 = max(memo(i+1, j, grid[i][j]), memo(i, j+1, grid[i][j]));\n else\n ans1 = grid[i][j] - prev + max(memo(i+1, j, grid[i][j]), memo(i, j+1, grid[i][j]));\n \n // do not take\n int ans2 = max(memo(i+1, j, prev), memo(i, j+1, prev));\n return dp[key] = max(ans1, ans2);\n }\n \n // SOL-1: RECURSION -- TLE -- 505 / 564 test cases passed. -- 89.53%\n int dfs(const vector<vector<int>>& grid, int i, int j, int prev)\n {\n if ( i>=grid.size() || j>=grid[0].size() )\n return 0;\n \n // take\n int ans1 = -1;\n if ( prev == -1 )\n ans1 = max(dfs(grid, i+1, j, grid[i][j]), dfs(grid,i, j+1, grid[i][j]));\n else\n ans1 = grid[i][j] - prev + max(dfs(grid, i+1, j, grid[i][j]), dfs(grid,i, j+1, grid[i][j]));\n \n // do not take\n int ans2 = max(dfs(grid, i+1, j, prev), dfs(grid, i, j+1, prev));\n return max(ans1, ans2);\n }\n \n // TC: O(m*n + m*n) = O(m*n), SC: O(1).\n bool isStrictlyIncreasing(const vector<vector<int>>& grid, int &ans)\n {\n // validate all rows.\n for ( int i=0; i<grid.size(); i++ )\n {\n unordered_set<int> hs;\n for ( int j=0; j<grid[i].size(); j++ )\n {\n int x = grid[i][j];\n for ( int num: hs ) {\n if ( num <= x )\n return false;\n ans = max(ans, x-num);\n }\n hs.insert(x);\n }\n }\n \n // validate all columns.\n for ( int j=0; j<grid[0].size(); j++ )\n {\n unordered_set<int> hs;\n for ( int i=0; i<grid.size(); i++ )\n {\n int x = grid[i][j];\n for ( int num : hs ) {\n if ( num <= x )\n return false;\n ans = max(ans, x-num);\n }\n hs.insert(x);\n }\n }\n \n return true;\n }\n};\n``` | 1 | 0 | ['Dynamic Programming'] | 0 |
maximum-difference-score-in-a-grid | Very Easy Solution in Python with clear approach -> time o(n*n), space(o(1)) | very-easy-solution-in-python-with-clear-kodhd | Intuition\n Describe your first thoughts on how to solve this problem. \nIf you observe, you will notice that the answer will be path independent.\nyou just nee | nketu06 | NORMAL | 2024-05-16T01:03:30.744350+00:00 | 2024-05-16T01:03:30.744373+00:00 | 166 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf you observe, you will notice that the answer will be path independent.\nyou just need to find that max difference of grid[i][j] with the smallest value till i,j \n\nin other word if suppose current point is 2,3 then you need the samallest value till 2,3 index and substract with grid[2][3]\n\nDo this for all elements of 2D array, return the max of it\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIn grid itself i am storing minimum value till that point and compares with previous, then find maximum of all\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n(N*N) since going to all cell once\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nconstant or o(1)\n\n# Code\n```\nclass Solution:\n def maxScore(self, grid: List[List[int]]) -> int:\n row=len(grid)\n col=len(grid[0])\n\n ans=-float(\'inf\')\n\n for i in range(row):\n for j in range(col):\n top= grid[i-1][j] if i>0 else float(\'inf\')\n left= grid[i][j-1] if j>0 else float(\'inf\')\n \n ans=max(ans,grid[i][j]-top,grid[i][j]-left)\n grid[i][j]=min(grid[i][j],top,left)\n return ans\n \n\n \n``` | 1 | 0 | ['Array', 'Dynamic Programming', 'Python3'] | 2 |
maximum-difference-score-in-a-grid | Maximum Difference Score in a Grid 🚦 Optimal Dynamic Programming Approach | maximum-difference-score-in-a-grid-optim-asd2 | \n## Intuition\nThe goal is to find the maximum difference between the value of a cell and the minimum value of its adjacent upper or left cell in a given grid. | lebon | NORMAL | 2024-05-14T23:24:35.011806+00:00 | 2024-05-14T23:24:35.011828+00:00 | 12 | false | \n## Intuition\nThe **goal** is to find the maximum difference between the value of a cell and the minimum value of its adjacent upper or left cell in a given grid. \n\nThe **challenge** is to efficiently calculate this maximum difference while updating the grid in place to keep track of the minimum values encountered so far. This can be achieved by iterating through the grid and applying **dynamic programming principles** to store and update intermediate results.\n\n## Approach\n1. **Initialization**:\n - Initialize `res` with a very small value (`-1000000`) to store the maximum score found during the iteration.\n - Determine the number of rows (`m`) and columns (`n`) in the grid.\n - Create a mutable copy of the input grid to allow modifications.\n\n2. **Iterate Through the Grid**:\n - Use nested loops to traverse each cell in the grid. The outer loop iterates through each row (`i`), and the inner loop iterates through each column (`j`).\n\n3. **Calculate `pre`**:\n - For each cell, calculate the minimum value (`pre`) between the cell above (`grid[i-1][j]`) if it exists and the cell to the left (`grid[i][j-1]`) if it exists.\n - If there is no cell above (`i == 0`) or no cell to the left (`j == 0`), use a large value (`1000000`) instead.\n\n4. **Update the Result `res`**:\n - Update `res` with the maximum value between the current `res` and the difference between the current cell value (`grid[i][j]`) and `pre`.\n\n5. **Update the Current Cell Value**:\n - If `pre` is less than the current cell value, update the current cell value to `pre`. This ensures that future calculations consider the minimum path values.\n\n6. **Return the Result**:\n - After iterating through the entire grid, return the maximum score (`res`).\n\n## Complexity\n- **Time complexity**:\n - The time complexity is $$O(m \\times n)$$, where $$m$$ is the number of rows and $$n$$ is the number of columns in the grid. This is because each cell in the grid is visited once.\n\n- **Space complexity**:\n - The space complexity is $$O(1)$$ beyond the input storage. The input grid is modified in place, and only a few additional variables are used.\n\n\n\n\n## Code\n```swift []\nclass Solution {\n func maxScore(_ grid: [[Int]]) -> Int {\n // Initialize the result with a very small value\n var res = -1000000\n // Get the number of rows and columns in the matrix\n let m = grid.count\n let n = grid[0].count\n \n // Create a mutable copy of the input matrix\n var grid = grid\n \n // Iterate through each cell in the matrix\n for i in 0..<m {\n for j in 0..<n {\n // Determine the minimum value between the cell above (if exists) and the cell to the left (if exists)\n let pre = min(\n i > 0 ? grid[i - 1][j] : 1000000, // If i > 0, take the value from the cell above; otherwise, use a large value\n j > 0 ? grid[i][j - 1] : 1000000 // If j > 0, take the value from the cell to the left; otherwise, use a large value\n )\n \n // Update the result with the maximum difference found so far\n res = max(res, grid[i][j] - pre)\n \n // If the previous minimum value is less than the current cell value, update the current cell value\n if pre < grid[i][j]) {\n grid[i][j] = pre\n }\n }\n }\n \n // Return the maximum difference found\n return res\n }\n}\n | 1 | 0 | ['Array', 'Dynamic Programming', 'Swift'] | 0 |
maximum-difference-score-in-a-grid | Easy DP Solution :) | easy-dp-solution-by-user20222-ggdy | Code\n\nclass Solution {\npublic:\nvector<vector<vector<int>>>dp;\n int f(vector<vector<int>>&grid,int i,int j,int s){\n if(i>=grid.size()||j>=grid[0] | user20222 | NORMAL | 2024-05-14T04:52:51.119035+00:00 | 2024-05-14T04:52:51.119057+00:00 | 88 | false | # Code\n```\nclass Solution {\npublic:\nvector<vector<vector<int>>>dp;\n int f(vector<vector<int>>&grid,int i,int j,int s){\n if(i>=grid.size()||j>=grid[0].size()){\n if(s==2)return 0;\n return -1e6;\n }\n if(dp[i][j][s]!=-1e9)return dp[i][j][s];\n int val = 0;\n if(s){\n val = max({grid[i][j],f(grid,i+1,j,2),f(grid,i,j+1,2)});\n return dp[i][j][s]=val;\n }\n val = max({f(grid,i+1,j,s),f(grid,i,j+1,s),f(grid,i+1,j,1)-grid[i][j],f(grid,i,j+1,1)-grid[i][j]});\n return dp[i][j][s]=val;\n }\n int maxScore(vector<vector<int>>& grid) {\n dp.assign(grid.size(),vector<vector<int>>(grid[0].size(),vector<int>(3,-1e9)));\n return f(grid,0,0,0); \n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
maximum-difference-score-in-a-grid | Easy Java Solution || Dynamic Programing | easy-java-solution-dynamic-programing-by-qr2b | 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 | ravikumar50 | NORMAL | 2024-05-13T06:47:40.563337+00:00 | 2024-05-13T06:47:40.563369+00:00 | 101 | 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```\nclass Solution {\n public int maxScore(List<List<Integer>> arr) {\n int n = arr.size();\n int m = arr.get(0).size();\n int dp[][] = new int[n][m];\n int ans = -(int)(1e9);\n for(int j=0; j<m; j++){\n int diff = -(int)(1e9);\n for(int k=j+1; k<m; k++){\n diff = Math.max(diff,arr.get(n-1).get(k)-arr.get(n-1).get(j));\n }\n dp[n-1][j] = diff;\n ans = Math.max(ans,dp[n-1][j]);\n }\n\n for(int i=0; i<n; i++){\n int diff = -(int)(1e9);\n for(int k=i+1; k<n; k++){\n diff = Math.max(diff,arr.get(k).get(m-1)-arr.get(i).get(m-1));\n }\n dp[i][m-1] = diff;\n ans = Math.max(ans,dp[i][m-1]);\n }\n\n dp[n-1][m-1] = 0;\n\n for(int i=n-2; i>=0; i--){\n for(int j=m-2; j>=0; j--){\n int a = arr.get(i+1).get(j)-arr.get(i).get(j);\n int b = arr.get(i).get(j+1)-arr.get(i).get(j);\n\n int x = Math.max(a,a+dp[i+1][j]);\n int y = Math.max(b,b+dp[i][j+1]);\n dp[i][j] = Math.max(x,y);\n ans = Math.max(ans,dp[i][j]);\n }\n }\n\n return ans;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
maximum-difference-score-in-a-grid | 100% Fast Code | Simple Approach | 100-fast-code-simple-approach-by-ronak_r-25dk | Intuition\n Describe your first thoughts on how to solve this problem. \nThe idea is to store the minimum element encountered in the top and left portion for ea | Ronak_Ramuka | NORMAL | 2024-05-12T21:26:40.469440+00:00 | 2024-05-12T21:26:40.469457+00:00 | 110 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe idea is to store the minimum element encountered in the top and left portion for each position in the grid. Then, we calculate the final answer as the maximum difference between the stored minimum and the element at that position.\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maxScore(List<List<Integer>> grid) {\n int n = grid.size();\n int m = grid.get(0).size();\n int[][] dp = new int[n][m];\n dp[0][0] = grid.get(0).get(0);\n \n for (int i = 1; i < n; i++) {\n dp[i][0] = Math.min(dp[i - 1][0], grid.get(i).get(0));\n }\n \n for (int i = 1; i < m; i++) {\n dp[0][i] = Math.min(dp[0][i - 1], grid.get(0).get(i));\n }\n \n for (int i = 1; i < n; i++) {\n for (int j = 1; j < m; j++) {\n dp[i][j] = Math.min(grid.get(i).get(j),Math.min(dp[i - 1][j], dp[i][j - 1]));\n }\n }\n\n int ans = Integer.MIN_VALUE;\n \n for (int i = 1; i < n; i++) {\n ans = Math.max(ans, grid.get(i).get(0) - dp[i - 1][0]);\n }\n \n for (int i = 1; i < m; i++) {\n ans = Math.max(ans, grid.get(0).get(i) - dp[0][i - 1]);\n }\n \n for (int i = 1; i < n; i++) {\n for (int j = 1; j < m; j++) {\n ans = Math.max(ans, grid.get(i).get(j) - Math.min(dp[i - 1][j], dp[i][j - 1]));\n }\n }\n \n return ans;\n }\n}\n\n``` | 1 | 0 | ['Array', 'Dynamic Programming', 'Java'] | 0 |
maximum-difference-score-in-a-grid | c++ Solution || easy to understand || using memoization ✅✅ | c-solution-easy-to-understand-using-memo-1cpw | \n\n# Code\n\nclass Solution {\npublic:\n int dp[1002][1002];\n int func(int n, int m, int i, int j, vector<vector<int>>&grid){\n if(i>=n || j>=m) | Arzoo_singh | NORMAL | 2024-05-12T11:55:53.964236+00:00 | 2024-05-12T11:55:53.964275+00:00 | 147 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int dp[1002][1002];\n int func(int n, int m, int i, int j, vector<vector<int>>&grid){\n if(i>=n || j>=m) return 0;\n if(dp[i][j]!=-1) return dp[i][j];\n int right = INT_MIN, down = INT_MIN;\n if(i+1<n){\n down = grid[i+1][j]-grid[i][j] + func(n, m, i+1, j, grid);\n }\n if(j+1<m){\n right = grid[i][j+1]-grid[i][j] + func(n, m, i, j+1, grid);\n }\n return dp[i][j] = max(0, max(right, down));\n }\n int maxScore(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n memset(dp, -1, sizeof(dp));\n int ans = INT_MIN;\n int mx = INT_MIN;\n for(int i = 0; i < n; i++){\n for(int j = 0; j < m; j++){\n mx = max(mx, func(n, m, i, j, grid));\n if(i+1<n){\n ans = max(ans, grid[i+1][j]-grid[i][j]);\n }\n if(j+1<m){\n ans = max(ans, grid[i][j+1]-grid[i][j]);\n }\n }\n }\n if(mx==0) return ans;\n return mx;\n }\n};\n``` | 1 | 0 | ['Dynamic Programming', 'Memoization', 'C++'] | 0 |
maximum-difference-score-in-a-grid | Recursion || DP || Memoization | recursion-dp-memoization-by-birenamanta-dsvl | 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 | birenamanta | NORMAL | 2024-05-12T06:56:12.533425+00:00 | 2024-05-12T06:56:12.533462+00:00 | 136 | 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```\nclass Solution {\n private Integer dp[][];\n public int maxScore(List<List<Integer>> grid) {\n int m = grid.size() , n = grid.get(0).size();\n dp = new Integer[m][n];\n int max = Integer.MIN_VALUE;\n for(int i = 0 ; i < m ; i++){\n for(int j = 0 ; j < n ; j++){\n int temp = getMaxDiff(i,j,m,n,grid);\n max = Math.max(temp,max);\n }\n }\n return max;\n }\n public int getMaxDiff(int row,int col ,int m,int n,List<List<Integer>> grid){\n if(row >= m || col >= n) return Integer.MIN_VALUE;\n if(dp[row][col] != null) return dp[row][col]; \n int max = Integer.MIN_VALUE , ele = grid.get(row).get(col); \n int temp = Math.max(0 , getMaxDiff(row+1,col,m,n,grid));\n if(row +1 < m) max = Math.max(max , grid.get(row+1).get(col) - ele +temp);\n temp = Math.max(0,getMaxDiff(row,col+1 ,m,n,grid));\n if(col+1 < n) max = Math.max(max , grid.get(row).get(col + 1) - ele +temp);\n \n return dp[row][col] = max ;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
maximum-difference-score-in-a-grid | beats 100 % percent of users || weekly contest 397 | beats-100-percent-of-users-weekly-contes-sko6 | 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 | Saksham_chaudhary_2002 | NORMAL | 2024-05-12T04:36:16.128565+00:00 | 2024-05-12T04:36:16.128588+00:00 | 239 | 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```\nclass Solution:\n def maxScore(self, grid: List[List[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n \n # Initialize the maxFutureValue matrix\n maxFutureValue = [[float(\'-inf\')] * n for _ in range(m)]\n maxFutureValue[m - 1][n - 1] = grid[m - 1][n - 1]\n \n # Calculate the maxFutureValue matrix\n for i in range(m - 1, -1, -1):\n for j in range(n - 1, -1, -1):\n if i < m - 1:\n maxFutureValue[i][j] = max(maxFutureValue[i][j], maxFutureValue[i + 1][j])\n if j < n - 1:\n maxFutureValue[i][j] = max(maxFutureValue[i][j], maxFutureValue[i][j + 1])\n maxFutureValue[i][j] = max(maxFutureValue[i][j], grid[i][j])\n \n # Calculate the maxScore\n maxScore = float(\'-inf\')\n for i in range(m):\n for j in range(n):\n if i < m - 1:\n maxScore = max(maxScore, maxFutureValue[i + 1][j] - grid[i][j])\n if j < n - 1:\n maxScore = max(maxScore, maxFutureValue[i][j + 1] - grid[i][j])\n \n return maxScore\n\n``` | 1 | 0 | ['Python3'] | 0 |
maximum-difference-score-in-a-grid | Solved in c using dynamic programming, Bottom up approach | solved-in-c-using-dynamic-programming-bo-1fbh | \n\n# Complexity\n- Time complexity:\n O(n^2)\n\n- Space complexity:\n O(n^2) \n\n# Code\n\nint max(int a,int b){\n return a>b?a:b;\n}\n\nint maxScore(int** | yeshwanth_123 | NORMAL | 2024-05-12T04:28:31.749861+00:00 | 2024-05-12T04:28:31.749879+00:00 | 65 | false | \n\n# Complexity\n- Time complexity:\n $$O(n^2)$$\n\n- Space complexity:\n $$O(n^2)$$ \n\n# Code\n```\nint max(int a,int b){\n return a>b?a:b;\n}\n\nint maxScore(int** grid, int gridSize, int* gridColSize) {\n int res=-1e9;\n int col=*gridColSize;\n int row=gridSize;\n int** dp=malloc(sizeof(int*)*gridSize);\n for(int i=0;i<gridSize;i++){\n dp[i]=malloc(sizeof(int)*gridColSize[i]);\n }\n for(int i=0;i<col;i++){\n dp[gridSize-1][i]=-1e9;\n }\n \ndp[row-1][col-1]=-1e9;\nfor(int i=col - 2 ; i>=0;i--){\n dp[row-1][i]=max(dp[row-1][i+1]+grid[row-1][i+1]-grid[row-1][i],grid[row-1][i+1]-grid[row-1][i] );\n}\n\nfor(int i=row-2;i>=0;i--){\n dp[i][col-1]=max(dp[i+1][col-1]+grid[i+1][col-1]-grid[i][col-1],grid[i+1][col-1]-grid[i][col-1]);\n}\n\nfor(int i=row-2;i>=0;i--){\n for(int j=col-2;j>=0;j--){\n int bottom=dp[i+1][j];\n int right=dp[i][j+1];\n int b=grid[i+1][j]-grid[i][j];\n int d=grid[i][j+1]-grid[i][j];\n int max1=max(bottom+b,b);\n int max2=max(right+d,d);\n dp[i][j]=max(max1,max2); \n }\n}\nfor(int i=0;i<row;i++){\n for(int j=0;j<col;j++){\n res=max(res,dp[i][j]);\n }\n }\nreturn res;\n}\n``` | 1 | 0 | ['Dynamic Programming', 'Memoization', 'C'] | 0 |
maximum-difference-score-in-a-grid | 🔥💯| Full Java Solution | Explanation | ✅🎯 | full-java-solution-explanation-by-anushd-l2ai | Intuition\nThe problem seems to be about finding the maximum score that can be obtained from a grid of integers. The intuition is to use dynamic programming to | Chandrikasharma16 | NORMAL | 2024-05-12T04:20:44.689553+00:00 | 2024-05-12T04:20:44.689569+00:00 | 57 | false | # Intuition\nThe problem seems to be about finding the maximum score that can be obtained from a grid of integers. The intuition is to use dynamic programming to keep track of the maximum future value that can be obtained from each cell in the grid.\n\n# Approach\n1. Initialize a 2D array `maxFutureValue` of the same size as the grid with all values set to `Integer.MIN_VALUE`.\n2. Set the value of the bottom-right cell of `maxFutureValue` to the maximum of 0 and the value of the corresponding cell in the grid.\n3. Iterate over the grid in reverse row-major order. For each cell:\n - If it\'s not the last row, update its value in `maxFutureValue` to the maximum of its current value and the value of the cell below it in `maxFutureValue`.\n - If it\'s not the last column, update its value in `maxFutureValue` to the maximum of its current value and the value of the cell to its right in `maxFutureValue`.\n - Update its value in `maxFutureValue` to the maximum of its current value and the value of the corresponding cell in the grid.\n4. Initialize `maxScore` to `Integer.MIN_VALUE`.\n5. Iterate over the grid in row-major order. For each cell:\n - If it\'s not the last row, update `maxScore` to the maximum of its current value and the difference between the value of the cell below it in `maxFutureValue` and the value of the corresponding cell in the grid.\n - If it\'s not the last column, update `maxScore` to the maximum of its current value and the difference between the value of the cell to its right in `maxFutureValue` and the value of the corresponding cell in the grid.\n6. Return `maxScore`.\n\n# Complexity\n- Time complexity: The time complexity is $$O(mn)$$, where `m` and `n` are the number of rows and columns in the grid, respectively. This is because you\'re iterating over each cell in the grid twice.\n- Space complexity: The space complexity is also $$O(mn)$$, as you\'re using a 2D array of the same size as the grid to store the maximum future values.\n\n# Code\n``` Java []\nclass Solution {\n public int maxScore(List<List<Integer>> grid) {\n int m = grid.size();\n int n = grid.get(0).size();\n int[][] maxFutureValue = new int[m][n];\n for (int[] row : maxFutureValue) {\n Arrays.fill(row, Integer.MIN_VALUE);\n }\n maxFutureValue[m - 1][n - 1] = Math.max(0, grid.get(m - 1).get(n - 1));\n for (int i = m - 1; i >= 0; i--) {\n for (int j = n - 1; j >= 0; j--) {\n if (i < m - 1) {\n maxFutureValue[i][j] = Math.max(maxFutureValue[i][j], maxFutureValue[i + 1][j]);\n }\n if (j < n - 1) {\n maxFutureValue[i][j] = Math.max(maxFutureValue[i][j], maxFutureValue[i][j + 1]);\n }\n maxFutureValue[i][j] = Math.max(maxFutureValue[i][j], grid.get(i).get(j));\n }\n }\n int maxScore = Integer.MIN_VALUE;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (i < m - 1) {\n maxScore = Math.max(maxScore, maxFutureValue[i + 1][j] - grid.get(i).get(j));\n }\n if (j < n - 1) {\n maxScore = Math.max(maxScore, maxFutureValue[i][j + 1] - grid.get(i).get(j));\n }\n }\n }\n return maxScore;\n }\n}\n\n``` | 1 | 0 | ['Java'] | 0 |
maximum-difference-score-in-a-grid | C++ soln || using DP | c-soln-using-dp-by-anjali234-plj5 | \n\n# Code\n\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n \n int n = grid.size(), m = grid[0].size();\n vect | anjali234 | NORMAL | 2024-05-12T04:14:32.631267+00:00 | 2024-05-12T04:14:32.631287+00:00 | 46 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n \n int n = grid.size(), m = grid[0].size();\n vector<vector<int>>dp(n,vector<int>(m,INT_MIN));\n int res = INT_MIN;\n \n dp[0][0] = 0;\n \n int mi = grid[0][0];\n for(int j = 1; j < m; j++)\n {\n dp[0][j] = max(dp[0][j], grid[0][j] - mi);\n mi = min(grid[0][j],mi);\n res = max(res, dp[0][j]);\n }\n \n mi = grid[0][0];\n for(int i = 1; i < n; i++)\n {\n dp[i][0]= max(dp[i][0], grid[i][0]-mi);\n mi = min(mi,grid[i][0]);\n res = max(res, dp[i][0]);\n }\n \n \n \n for(int i = 1; i < n; i++)\n {\n for(int j = 1; j < m; j++)\n {\n int d1 = grid[i][j] - grid[i][j-1];\n int d2 = grid[i][j] - grid[i-1][j];\n \n dp[i][j] = max(dp[i][j], max(d1,d2));\n dp[i][j] = max(dp[i][j], max(d1+dp[i][j-1], d2+dp[i-1][j] ));\n \n res = max(res,dp[i][j]);\n }\n }\n \n return res;\n }\n};\n``` | 1 | 0 | ['Dynamic Programming', 'Matrix', 'C++'] | 0 |
maximum-difference-score-in-a-grid | Simple | Minimum top-left | DP | simple-minimum-top-left-dp-by-lovung-fpwv | Intuition\nDynamic Programming\n\n# Approach\ndp[i][j] will help to save value of minimum value of the top-left rectangle.\n\nMax score of jumping to have the d | lovung | NORMAL | 2024-05-12T04:11:16.157336+00:00 | 2024-05-12T04:20:39.420469+00:00 | 36 | false | # Intuition\nDynamic Programming\n\n# Approach\n`dp[i][j]` will help to save value of minimum value of the top-left rectangle.\n\nMax score of jumping to have the destination at a cell (i, j) is the different between `grid[i][j]` and minimum number in the top-left rectangle (except (i, j) because requirement `you have to make at least one move`). That\'s why I calculated `res = max(res, grid[i][j]-val)` before `dp[i][j] = min(val, grid[i][j])`.\n\nExample:\n`grid = [[9,5,7,3],[8,9,6,1],[6,7,14,3],[2,5,3,1]]`\nMax Score at (2,2) is `14-5` because 5 is the minimum value in the retangle from (0,0) to (2,2).\n\n\n\n# Complexity\n- Time complexity: `O(m*n)`\n- Space complexity: `O(m*n)`\n\n# Code\n```\nfunc maxScore(grid [][]int) int {\n\tm, n := len(grid), len(grid[0])\n\tdp := make([][]int, m)\n\tres := math.MinInt\n\tfor i := range m {\n\t\tdp[i] = make([]int, n)\n\t}\n\tfor i := 0; i < m; i++ {\n\t\tfor j := 0; j < n; j++ {\n\t\t\tval := math.MaxInt\n\t\t\tif In(grid, i-1, j) {\n\t\t\t\tval = min(val, dp[i-1][j])\n\t\t\t}\n\t\t\tif In(grid, i, j-1) {\n\t\t\t\tval = min(val, dp[i][j-1])\n\t\t\t}\n\t\t\tres = max(res, grid[i][j]-val)\n\t\t\tdp[i][j] = min(val, grid[i][j])\n\t\t}\n\t}\n\treturn res\n}\n\nfunc In[T any](mat [][]T, i, j int) bool {\n\treturn i >= 0 && i < len(mat) &&\n\t\tj >= 0 && (len(mat) == 0 || j < len(mat[0]))\n}\n``` | 1 | 0 | ['Go'] | 0 |
maximum-difference-score-in-a-grid | ✅C++ Accepted | Suffix Maxima | Easy⛳ | c-accepted-suffix-maxima-easy-by-manii15-nfm0 | Add your space complexity here, e.g. O(n) \n\n# Code\n\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int n = grid.size(), | manii15 | NORMAL | 2024-05-12T04:06:22.851820+00:00 | 2024-05-12T04:06:22.851849+00:00 | 26 | false | <!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int n = grid.size(), m = grid[0].size();\n vector<vector<int>> large(n,vector<int>(m));\n large[n-1][m-1] = grid[n-1][m-1];\n \n for(int i=n-2;i>=0;i--) large[i][m-1] = max(large[i+1][m-1],grid[i][m-1]);\n for(int i=m-2;i>=0;i--) large[n-1][i] = max(large[n-1][i+1],grid[n-1][i]);\n\n for(int i=n-2;i>=0;i--){\n for(int j=m-2;j>=0;j--){\n large[i][j] = max({grid[i][j],large[i+1][j],large[i][j+1]});\n }\n }\n \n int ans = INT_MIN;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){ \n if(i+1 < n) ans = max(ans,large[i+1][j] - grid[i][j]);\n if(j+1 < m) ans = max(ans,large[i][j+1] - grid[i][j]);\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
maximum-difference-score-in-a-grid | Using Maximum element || Esay || Understandable | using-maximum-element-esay-understandabl-g1a7 | 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 | jimish6600 | NORMAL | 2024-05-12T04:04:10.105243+00:00 | 2024-05-12T04:04:10.105276+00:00 | 176 | 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```\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n vector<vector<int>> ans(grid.size(),vector<int> (grid[0].size(),INT_MIN));\n int s = INT_MIN;\n for(int i=0;i<grid.size();i++){\n s = INT_MIN;\n for(int j=grid[0].size()-1;j>=0;j--){\n \n s = max(s,grid[i][j]);\n ans[i][j] = s;\n }\n }\n s = INT_MIN;\n for(int i=0;i<ans[0].size();i++){\n s = INT_MIN;\n for(int j=ans.size()-1;j>=0;j--){\n \n s = max(s,ans[j][i]);\n ans[j][i] = max(s,ans[j][i]);\n }\n }\n int fans = INT_MIN;\n for(int i=0;i<grid.size();i++){\n for(int j=0;j<grid[0].size();j++){\n cout<<ans[i][j]<<" ";\n if(i<grid.size()-1){\n if(ans[i][j] == ans[i+1][j]){\n fans = max(fans,ans[i][j] - grid[i][j]);\n }else{\n fans = max(fans,ans[i+1][j] - grid[i][j]);\n }\n }\n \n if(j<grid[0].size()-1){\n if(ans[i][j] == ans[i][j+1]){\n fans = max(fans,ans[i][j] - grid[i][j]);\n }else{\n fans = max(fans,ans[i][j+1] - grid[i][j]);\n }\n }\n \n }\n // cout<<endl;\n \n }\n return fans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
maximum-difference-score-in-a-grid | Java Clean Solution | java-clean-solution-by-shree_govind_jee-sl5f | Complexity\n- Time complexity:O(n^2)\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# | Shree_Govind_Jee | NORMAL | 2024-05-12T04:03:20.705958+00:00 | 2024-05-12T04:03:20.705991+00:00 | 298 | false | # Complexity\n- Time complexity:$$O(n^2)$$\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 public int maxScore(List<List<Integer>> grid) {\n int row = grid.size();\n int col = grid.get(0).size();\n\n int[][] dp = new int[row][col];\n for (int[] d : dp) {\n Arrays.fill(d, Integer.MIN_VALUE);\n }\n\n dp[row - 1][col - 1] = grid.get(row - 1).get(col - 1);\n for (int i = row - 1; i >= 0; i--) {\n for (int j = col - 1; j >= 0; j--) {\n if (i < row - 1) {\n dp[i][j] = Math.max(dp[i][j], dp[i + 1][j]);\n }\n if (j < col - 1) {\n dp[i][j] = Math.max(dp[i][j], dp[i][j + 1]);\n }\n dp[i][j] = Math.max(dp[i][j], grid.get(i).get(j));\n }\n }\n\n int max = Integer.MIN_VALUE;\n for (int i = 0; i < row; i++) {\n for (int j = 0; j < col; j++) {\n if (i < row - 1) {\n max = Math.max(max, dp[i + 1][j] - grid.get(i).get(j));\n }\n if (j < col - 1) {\n max = Math.max(max, dp[i][j + 1] - grid.get(i).get(j));\n }\n }\n }\n return max;\n }\n}\n``` | 1 | 0 | ['Array', 'Math', 'Dynamic Programming', 'Recursion', 'Matrix', 'Java'] | 1 |
maximum-difference-score-in-a-grid | Matrix DP | matrix-dp-by-rajesh_sv-05n6 | Code\n\nclass Solution:\n def maxScore(self, grid: List[List[int]]) -> int:\n # DP\n # Time Complexity: O(mn)\n # Space Complexity: O(mn | rajesh_sv | NORMAL | 2024-05-12T04:01:56.154783+00:00 | 2024-05-12T17:50:17.462303+00:00 | 38 | false | # Code\n```\nclass Solution:\n def maxScore(self, grid: List[List[int]]) -> int:\n # DP\n # Time Complexity: O(mn)\n # Space Complexity: O(mn)\n m, n = len(grid), len(grid[0])\n dp = [[-inf] * (n+1) for _ in range(m+1)]\n ans = -inf\n for i in range(1, m+1):\n for j in range(1, n+1):\n if i == 1 and j == 1: continue\n if i != 1:\n dp[i][j] = grid[i-1][j-1] - grid[i-2][j-1] + max(0, dp[i-1][j])\n if j != 1:\n dp[i][j] = max(dp[i][j], grid[i-1][j-1] - grid[i-1][j-2] + max(0, dp[i][j-1]))\n ans = max(ans, dp[i][j])\n return ans\n``` | 1 | 0 | ['Dynamic Programming', 'Python3'] | 0 |
maximum-difference-score-in-a-grid | Easy Solution using DP C++ | easy-solution-using-dp-c-by-visheshjinda-klpk | Intuition\n The problem involves traversing a grid to find the maximum score attainable by following certain rules. Initially, we might consider a brute-force a | visheshjindal368 | NORMAL | 2024-05-12T04:01:42.222696+00:00 | 2024-05-12T04:01:42.222731+00:00 | 429 | false | # Intuition\n The problem involves traversing a grid to find the maximum score attainable by following certain rules. Initially, we might consider a brute-force approach of exploring all possible paths from the starting point to the ending point, but this would be inefficient. Instead, we can leverage dynamic programming to efficiently compute the maximum score.\n\n# Approach\nWe approach this problem using dynamic programming. We create a 2D DP array to store the maximum score attainable from each cell. We start from the bottom-right corner of the grid and work our way towards the top-left corner. For each cell, we compute the maximum score by considering the scores from the adjacent cells and the current cell\'s score. We update the DP array accordingly. Once we have filled the DP array, we traverse the grid again to find the maximum score while considering the constraints of not visiting cells that have been visited in the previous traversal.\n\n# Complexity\n- Time complexity:\n The time complexity of our approach is O(n * m), where n is the number of rows and m is the number of columns in the grid. This is because we traverse the grid twice: once to fill the DP array and once to find the maximum score. In each traversal, we visit each cell once, leading to a total time complexity of O(n * m).\n\n- Space complexity:\n The space complexity of our approach is also O(n * m). This is because we use a 2D DP array to store intermediate results. The size of this array is proportional to the size of the input grid, which is n * m. Therefore, the space complexity is O(n * m).\n\n\n# Code\n```\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int rows = grid.size();\nint cols = grid[0].size();\n\nstd::vector<std::vector<int>> dp(rows, std::vector<int>(cols, std::numeric_limits<int>::min()));\ndp[rows - 1][cols - 1] = grid[rows - 1][cols - 1];\n\nfor (int i = rows - 1; i >= 0; --i) {\nfor (int j = cols - 1; j >= 0; --j){\nif (i < rows - 1)\ndp[i][j] = std::max(dp[i][j], dp[i + 1][j]);\nif (j < cols - 1)\ndp[i][j] = std::max(dp[i][j], dp[i][j + 1]);\ndp[i][j] = std::max(dp[i][j], grid[i][j]);\n}\n}\n\nint maxscore = std::numeric_limits<int>::min();\nfor (int i = 0; i < rows; ++i) {\nfor (int j = 0; j < cols; ++j) {\nif (i < rows - 1)\nmaxscore = std::max(maxscore, dp[i + 1][j] - grid[i][j]);\nif (j < cols - 1)\nmaxscore = std::max(maxscore, dp[i][j + 1] - grid[i][j]);\n}\n}\nreturn maxscore;\n }\n};\n\n\n``` | 1 | 0 | ['C++'] | 2 |
maximum-difference-score-in-a-grid | [C++] Intuition - Consider only a single step | c-intuition-consider-only-a-single-step-12vv3 | Intuition - \nLet\'s consider a series a->b, b->c, c->d, d->e. The total sum then would be b-a + c-b + d-c + e-d , which is finally same as e-a. So the differe | saiteja_balla0413 | NORMAL | 2024-05-12T04:01:03.003287+00:00 | 2024-05-12T04:03:57.105022+00:00 | 367 | false | **Intuition** - \nLet\'s consider a series a->b, b->c, c->d, d->e. The total sum then would be b-a + c-b + d-c + e-d , which is finally same as e-a. So the difference of ending and starting points would add to the result and the ending point should be the maximum value in the subgrid ` grid[i...m][j...n]`. \n\n**Approach** - \n\n`dp[i][j]` stores the maximum value in the subgrid ` grid[i...m][j...n]` and for every ` grid[i][j]` consider it as a starting point and update the result.\n\n**Code [C++]**\n```\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n \n int m=grid.size(),n=grid[0].size();\n \n //dp[i][j] -> maximum element in the subgrid [i..m][j..n]\n vector<vector<int>> dp(m,vector<int>(n,INT_MAX));\n \n int res=INT_MIN;\n\n for(int i=m-1;i>=0;i--)\n {\n for(int j=n-1;j>=0;j--)\n {\n \n int maxi=INT_MIN;\n \n if(j+1<n)\n maxi=max(maxi, dp[i][j+1]);\n if(i+1<m)\n maxi=max(maxi, dp[i+1][j]);\n \n //no bottom and right element \n if(maxi==INT_MIN){\n \n dp[i][j]=grid[i][j];\n continue;\n }\n \n //update the result \n res=max(res, maxi - grid[i][j]);\n \n //update the maximum element in the subgrid\n dp[i][j]=max(maxi, grid[i][j]);\n }\n }\n \n return res;\n \n }\n \n};\n```\n\n**Please upvote if you like the solution**\n | 1 | 0 | [] | 2 |
maximum-difference-score-in-a-grid | [C++] Beats 100% runtime single dimension DP array | c-beats-100-runtime-single-dimension-dp-36s9w | IntuitionVerify that going from a cell 1 to 5 to 9 is the same as going from a cell 1 to 9:
5 - 1 + 9 - 5 = 9 - 1Therefore we only need to find the maximum diff | DuarteBarbosaRibeiro | NORMAL | 2025-04-02T15:23:45.177988+00:00 | 2025-04-02T15:23:45.177988+00:00 | 2 | false | # Intuition
Verify that going from a cell 1 to 5 to 9 is the same as going from a cell 1 to 9:
5 - 1 + 9 - 5 = 9 - 1
Therefore we only need to find the maximum difference between any cell and a cell to the bottom or right of it.
# Approach
We can use an array maximum with size of cols to keep track of the maximum element to the bottom or right for the row below the one currently being processed.
If we update the array right to left, part of the array will be updated to the current row and we can read from it to get the maximum value for the cell on the right of the one being processed.
# Complexity
- Time complexity:
O(rows * cols)
- Space complexity:
O(cols)
# Code
```cpp []
class Solution {
public:
int maxScore(vector<vector<int>>& grid) {
int rows = grid.size(), cols = grid[0].size(), result = INT_MIN;
vector<int> maximum(cols);
maximum[cols - 1] = grid[rows - 1][cols - 1];
for (int x = cols - 2; x >= 0; --x) {
result = max(result, maximum[x + 1] - grid[rows - 1][x]);
maximum[x] = max(grid[rows - 1][x], maximum[x + 1]);
}
for (int y = rows - 2; y >= 0; --y) {
result = max(result, maximum[cols - 1] - grid[y][cols - 1]);
maximum[cols - 1] = max(grid[y][cols - 1], maximum[cols - 1]);
for (int x = cols - 2; x >= 0; --x) {
maximum[x] = max(maximum[x], maximum[x + 1]);
result = max(result, maximum[x] - grid[y][x]);
maximum[x] = max(maximum[x], grid[y][x]);
}
}
return result;
}
};
```
Feel free to ask questions if you like my solution! | 0 | 0 | ['C++'] | 0 |
maximum-difference-score-in-a-grid | C++ | beats 66% | DP - Tabulation | c-beats-66-dp-tabulation-by-aryan-ki-cod-0wye | Approachuse recurrence
dp[i][j] = max(max(grid[i + 1][j], grid[i][j + 1]) -
grid[i][j] // 1 move
,
max(dp[i + 1][j] + grid[i + 1][j] - grid[i][j],
dp[i][j + 1] | Aryan-ki-codepanti | NORMAL | 2025-03-14T04:44:02.903503+00:00 | 2025-03-14T04:44:02.903503+00:00 | 3 | false | # Approach
<!-- Describe your approach to solving the problem. -->
use recurrence
dp[i][j] = max(max(grid[i + 1][j], grid[i][j + 1]) -
grid[i][j] // 1 move
,
max(dp[i + 1][j] + grid[i + 1][j] - grid[i][j],
dp[i][j + 1] + grid[i][j + 1] - grid[i][j]));
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
$$O(n*m)$$
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
$$O(n*m)$$
# Code
```cpp []
class Solution {
public:
int maxScore(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
vector<vector<int>> dp(m, vector<int>(n, -1e9));
// a[i][n-1]
for (int i = m - 2; i >= 0; i--)
dp[i][n - 1] =
max(dp[i][n - 1], max(grid[i + 1][n - 1] - grid[i][n - 1],
dp[i + 1][n - 1] + grid[i + 1][n - 1] -
grid[i][n - 1]));
// a[m-1][j]
for (int j = n - 2; j >= 0; j--)
dp[m - 1][j] =
max(dp[m - 1][j], max(grid[m - 1][j + 1] - grid[m - 1][j],
dp[m - 1][j + 1] + grid[m - 1][j + 1] -
grid[m - 1][j]));
for (int i = m - 2; i >= 0; i--) {
for (int j = n - 2; j >= 0; j--) {
dp[i][j] = max(max(grid[i + 1][j], grid[i][j + 1]) -
grid[i][j] // 1 move
,
max(dp[i + 1][j] + grid[i + 1][j] - grid[i][j],
dp[i][j + 1] + grid[i][j + 1] - grid[i][j]));
}
}
int ans = -1e9;
for (auto& x : dp)
for (auto& y : x)
ans = max(y, ans);
return ans;
}
};
``` | 0 | 0 | ['Array', 'Dynamic Programming', 'Matrix', 'C++'] | 0 |
maximum-difference-score-in-a-grid | scala solution | scala-solution-by-lyk4411-i1ho | IntuitionApproachComplexity
Time complexity:
Space complexity:
Codeor | lyk4411 | NORMAL | 2025-02-11T03:41:29.271230+00:00 | 2025-02-11T03:41:29.271230+00:00 | 1 | 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
```scala []
object Solution {
def maxScore(grid: List[List[Int]]): Int = {
val n = grid.size
val m = grid.head.size
val f = Array.fill(n, m)(Int.MaxValue)
var res = Int.MinValue
for{i <- 0 until n
j <- 0 until m}{
var min = Int.MaxValue
if(i > 0) min = Math.min(min, f(i - 1)(j))
if(j > 0) min = Math.min(min, f(i)(j - 1))
res = Math.max(res, grid(i)(j) - min)
f(i)(j) = Math.min(min, grid(i)(j))
}
res
}
}
```
or
```
def maxScore(grid: List[List[Int]]): Int = {
val n = grid.size
val m = grid.head.size
def helper(i: Int, j: Int, f: Array[Array[Int]], res: Int): Int = {
if (i >= n) res
else if (j >= m) helper(i + 1, 0, f, res)
else {
val min = (if (i > 0) Math.min(f(i - 1)(j), Int.MaxValue) else Int.MaxValue) min
(if (j > 0) Math.min(f(i)(j - 1), Int.MaxValue) else Int.MaxValue)
val newRes = Math.max(res, grid(i)(j) - min)
f(i)(j) = Math.min(min, grid(i)(j))
helper(i, j + 1, f, newRes)
}
}
val f = Array.fill(n, m)(Int.MaxValue)
helper(0, 0, f, Int.MinValue)
}
``` | 0 | 0 | ['Scala'] | 0 |
maximum-difference-score-in-a-grid | Maximum Difference Score in a Grid | maximum-difference-score-in-a-grid-by-na-4k67 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Naeem_ABD | NORMAL | 2025-01-13T18:47:22.332925+00:00 | 2025-01-13T18:47:22.332925+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
```python3 []
class Solution:
def maxScore(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
largestMax = [[0 for _ in range(cols)] for _ in range(rows)]
@cache
def findMax(row, col):
if row >= rows or col >= cols:
return -int(1E9)
largestMax[row][col] = max(findMax(row + 1, col), findMax(row, col + 1))
return max(grid[row][col], largestMax[row][col])
findMax(0, 0)
res = -int(1E9)
for row in range(rows):
for col in range(cols):
res = max(res, largestMax[row][col] - grid[row][col])
return res
``` | 0 | 0 | ['Python3'] | 0 |
maximum-difference-score-in-a-grid | [C++] Dynamic Programming | c-dynamic-programming-by-amanmehara-9pus | Code | amanmehara | NORMAL | 2025-01-11T06:08:25.568116+00:00 | 2025-01-11T06:08:25.568116+00:00 | 8 | false | # Code
```cpp []
class Solution {
public:
int maxScore(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
int max_score = INT_MIN;
vector<vector<int>> dp(m + 1, vector<int>(n + 1, INT_MAX));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
dp[i + 1][j + 1] = min(min(dp[i][j + 1], dp[i + 1][j]), min(i > 0 ? grid[i - 1][j] : INT_MAX, j > 0 ? grid[i][j - 1] : INT_MAX));
max_score = max(max_score, grid[i][j] - dp[i + 1][j + 1]);
}
}
return max_score;
}
};
``` | 0 | 0 | ['Dynamic Programming', 'C++'] | 0 |
maximum-difference-score-in-a-grid | Clever problem... Its DP but required paperwork first | clever-problem-its-dp-but-required-paper-o6au | IntuitionAt first, substraction might be hard. I think about jump game first, as I need to try each cell in that cell/column that could move to the current cell | minhtud04 | NORMAL | 2025-01-09T23:39:23.244383+00:00 | 2025-01-09T23:39:23.244383+00:00 | 8 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
At first, substraction might be hard. I think about jump game first, as I need to try each cell in that cell/column that could move to the current cell.
However, if we write the equation out:
- we jump our path as c1,c2,c3 --> all values in the middle will cancel itself (-c1 + c2 + -c2 + c3) -> turns out it just -c1 + c3(first and last value)
- With this, we just need to do prefSum template with minValue sofar ( could call this DP as prefSum just a specific DP type..?)
# 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
```python3 []
class Solution:
def maxScore(self, grid: List[List[int]]) -> int:
#m * n grid? - #DP for sure
ROW, COL = len(grid), len(grid[0])
maxVal = float("-inf")
for c in range(1, COL):
maxVal = max(maxVal, grid[0][c] - grid[0][c-1])
grid[0][c] = min(grid[0][c-1], grid[0][c])
for r in range(1, ROW):
maxVal = max(maxVal, grid[r][0] - grid[r-1][0])
grid[r][0] = min(grid[r-1][0], grid[r][0])
for r in range(1, ROW):
for c in range(1, COL):
curBestChoice = grid[r][c] - min(grid[r-1][c], grid[r][c-1])
maxVal = max(maxVal, curBestChoice)
grid[r][c] = min(grid[r][c], grid[r-1][c], grid[r][c-1])
return maxVal
#either choose or not choose
#Jump game?
``` | 0 | 0 | ['Python3'] | 0 |
maximum-difference-score-in-a-grid | SIMPLE RECURSION + MEMO C++ SOLUTION | simple-recursion-memo-c-solution-by-jeff-co0l | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Jeffrin2005 | NORMAL | 2025-01-05T03:50:40.973904+00:00 | 2025-01-05T03:50:40.973904+00:00 | 8 | 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 m, n;
vector<vector<int>> dp;
int solve(int i, int j, vector<vector<int>>& grid) {
if (i >= m || j >= n) return 0;
if (dp[i][j] != -1) return dp[i][j];
int pick1 = INT_MIN, pick2 = INT_MIN;
if (i + 1 < m) pick1 = grid[i + 1][j] - grid[i][j] + solve(i + 1, j, grid);
if (j + 1 < n) pick2 = grid[i][j + 1] - grid[i][j] + solve(i, j + 1, grid);
dp[i][j] = max(0, max(pick1, pick2));
return dp[i][j];
}
int maxScore(vector<vector<int>>& grid) {
m = grid.size();
n = grid[0].size();
dp = vector<vector<int>>(m, vector<int>(n, -1));
int maxi = INT_MIN;
int maxi1 = INT_MIN;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
maxi = max(maxi, solve(i, j, grid));
if (i + 1 < m) maxi1 = max(maxi1, grid[i + 1][j] - grid[i][j]);
if (j + 1 < n) maxi1 = max(maxi1, grid[i][j + 1] - grid[i][j]);
}
}
if (maxi == 0) return maxi1;
return maxi;
}
};
``` | 0 | 0 | ['C++'] | 0 |
maximum-difference-score-in-a-grid | DP | dp-by-linda2024-xu46 | 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 | linda2024 | NORMAL | 2024-12-04T23:52:43.248194+00:00 | 2024-12-04T23:52:43.248251+00:00 | 4 | 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```csharp []\npublic class Solution {\n public int MaxScore(IList<IList<int>> grid) {\n int rows = grid.Count, cols = grid[0].Count;\n if (rows == 0 || cols == 0)\n return 0;\n int[,] dp = new int[rows, cols];\n int res = int.MinValue;\n dp[0, 0] = grid[0][0];\n\n for(int j = 1; j < cols; j++)\n {\n res = Math.Max(res, grid[0][j] - dp[0,j-1]);\n dp[0,j] = Math.Min(grid[0][j], dp[0,j-1]);\n }\n\n for(int i = 1; i < rows; i++)\n {\n res = Math.Max(res, grid[i][0] - dp[i-1, 0]);\n dp[i, 0] = Math.Min(grid[i][0], dp[i-1, 0]);\n }\n\n for(int i = 1; i < rows; i++)\n for(int j = 1; j < cols; j++)\n {\n int pre = Math.Min(dp[i-1, j-1], Math.Min(dp[i-1, j], dp[i, j-1]));\n res = Math.Max(grid[i][j]-pre, res);\n dp[i,j] = Math.Min(pre, grid[i][j]);\n }\n\n return res;\n }\n}\n``` | 0 | 0 | ['C#'] | 0 |
maximum-difference-score-in-a-grid | Kotlin O(nm) time O(m) Space | kotlin-onm-time-om-space-by-bylazy-1iwr | Intuition\nThe maximum score for each cell is the difference between the cell\'s value and the minimum of the part of the matrix that is above and to the left o | bylazy | NORMAL | 2024-12-04T10:01:06.240196+00:00 | 2024-12-04T10:01:06.240231+00:00 | 2 | false | # Intuition\nThe maximum score for each cell is the difference between the cell\'s value and the minimum of the part of the matrix that is above and to the left of that cell.\n\n# Approach\nIn the array `m` we will store and maintain the minimum of the matrix up to and including the corresponding column.\n\n# Complexity\n- Time complexity:\nO(nm)\n\n- Space complexity:\nO(m)\n\n# Code\n```kotlin []\nclass Solution {\n fun maxScore(grid: List<List<Int>>): Int {\n //m[j] \u2014 minimum value in the first j+1 columns\n var m = IntArray(grid[0].size){Int.MAX_VALUE} \n var r = Int.MIN_VALUE //r for result\n for (i in 0..grid.lastIndex)\n for (j in 0..grid[0].lastIndex)\n //update max, the third argument is needed because the current minimum has not yet been updated\n r = maxOf(r, grid[i][j] - m[j], grid[i][j] - if (j == 0) Int.MIN_VALUE else m[j-1])\n .also{ m[j] = minOf(m[j], if (j == 0) Int.MAX_VALUE else m[j-1], grid[i][j]) } //update min\n return r\n }\n}\n``` | 0 | 0 | ['Kotlin'] | 0 |
maximum-difference-score-in-a-grid | Easy Memoization Solution | easy-memoization-solution-by-roy_b-nmao | Intuition\n Describe your first thoughts on how to solve this problem. \nI know it\'s a weird way, but it still works.\n# Approach\n Describe your approach to s | roy_b | NORMAL | 2024-11-22T04:55:46.316271+00:00 | 2024-11-22T04:55:46.316303+00:00 | 32 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI know it\'s a weird way, but it still works.\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```java []\nclass Solution {\n Integer[][][] dp;\n public int maxScore(List<List<Integer>> grid) {\n dp = new Integer[grid.size()][grid.get(0).size()][2];\n int max = Integer.MIN_VALUE;\n for(int i = 0; i<grid.size(); i++){\n for(int j = 0; j<grid.get(0).size(); j++){\n max = Math.max(max,f(grid,i,j,1)); \n }\n }\n return max;\n }\n public int f(List<List<Integer>> grid,int i,int j,int m){\n if(dp[i][j][m] != null){\n return dp[i][j][m];\n }\n if(m == 1){\n int down = Integer.MIN_VALUE;\n int right = Integer.MIN_VALUE;\n if(i < grid.size() - 1){\n down = f(grid,i+1,j,0)-grid.get(i).get(j);\n }\n if(j < grid.get(0).size() - 1){\n right = f(grid,i,j+1,0)-grid.get(i).get(j);\n }\n return dp[i][j][m] = Math.max(down,right);\n }\n int down = grid.get(i).get(j);\n int right = grid.get(i).get(j);\n if(i < grid.size() - 1){\n down = Math.max(down,down + f(grid,i+1,j,m)-grid.get(i).get(j));\n }\n if(j < grid.get(0).size() - 1){\n right = Math.max(right,right + f(grid,i,j+1,m)-grid.get(i).get(j));\n }\n return dp[i][j][m] = Math.max(down,right);\n }\n}\n``` | 0 | 0 | ['Array', 'Dynamic Programming', 'Recursion', 'Memoization', 'Matrix', 'C++', 'Java', 'Python3'] | 0 |
maximum-difference-score-in-a-grid | C++ Tabulation Easy solution | c-tabulation-easy-solution-by-user0374wc-t4xw | 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 | user0374Wc | NORMAL | 2024-11-15T14:54:37.326242+00:00 | 2024-11-15T14:54:37.326280+00:00 | 2 | 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```cpp []\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int n=grid.size();\n int m=grid[0].size();\n\n vector<vector<int>> dp(n,vector<int>(m));\n dp[0][0]=grid[0][0];\n int diff=INT_MIN;\n for(int i=1;i<m;i++)\n {\n diff=max(diff,grid[0][i]-grid[0][i-1]);\n dp[0][i]=min(dp[0][i-1],grid[0][i]);\n }\n\n for(int i=1;i<n;i++)\n {\n diff=max(diff,grid[i][0]-grid[i-1][0]);\n dp[i][0]=min(dp[i-1][0],grid[i][0]);\n }\n\n for(int i=1;i<n;i++)\n {\n for(int j=1;j<m;j++)\n {\n diff=max(diff,grid[i][j]-grid[i][j-1]);\n diff=max(diff,grid[i][j]-grid[i-1][j-1]);\n diff=max(diff,grid[i][j]-grid[i-1][j]);\n dp[i][j]=min({dp[i-1][j],dp[i][j-1],dp[i-1][j-1],grid[i][j]});\n }\n }\n int ans=INT_MIN;\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(grid[i][j]!=dp[i][j])\n {\n ans=max(ans,grid[i][j]-dp[i][j]);\n }\n \n }\n }\n\n return ans==INT_MIN?diff:ans;\n \n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-difference-score-in-a-grid | SIMPLE 5 LINE SOLUTION EVER ON INTERNET check out once if you don't believe me. | simple-5-line-solution-ever-on-internet-t8euj | Intuition\nwe just have to take record of initial and final position of each move and rest of the intermediate cells will always cancles each other \n\n# Approa | aniket_kumar_ | NORMAL | 2024-10-31T18:05:03.373850+00:00 | 2024-10-31T18:05:03.373877+00:00 | 6 | false | # Intuition\nwe just have to take record of initial and final position of each move and rest of the intermediate cells will always cancles each other \n\n# Approach\nfor each cell just look for the minimum value in it\'s to left part because max score can be made by min initial point and maximum end point\n\n# Complexity\n- Time complexity:\nO(N^2); but quite simple approach\n\n- Space complexity:\nO(1);\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n \n int result=INT_MIN;\n for(int i=0; i<grid.size(); i++){\n for(int j=0; j<grid[0].size(); j++){\n int min_value=INT_MAX;\n if(i==0 and j==0){\n continue;\n }\n if(i!=0){\n min_value=min(min_value,grid[i-1][j]);\n }\n if(j!=0){\n min_value=min(min_value,grid[i][j-1]);\n }\n result=max(result,grid[i][j]-min_value);\n grid[i][j]=min(grid[i][j],min_value);\n } \n }\n return result;\n }\n};\n``` | 0 | 0 | ['Array', 'Dynamic Programming', 'Matrix', 'C++'] | 0 |
maximum-difference-score-in-a-grid | Recursion + memoization || standard approach | recursion-memoization-standard-approach-3u16v | 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 | chanderveersinghchauhan08 | NORMAL | 2024-10-30T23:05:55.942021+00:00 | 2024-10-30T23:05:55.942043+00:00 | 4 | 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```cpp []\nclass Solution {\npublic:\n\n int f(int i , int j , vector<vector<int>> &grid , int n , int m , vector<vector<int>> &dp ){\n if(i>=n || j >=m || i < 0 || j < 0 ) return 0;\n if(dp[i][j] != -1) return dp[i][j];\n int right = -1e8;\n int down = -1e8;\n int op3 = -1e8;\n int op4 = -1e8;\n if(i+1 < n) right = grid[i+1][j] - grid[i][j] + f(i+1 , j , grid , n , m , dp);\n if(j+1 < m) down = grid[i][j+1] - grid[i][j] + f(i , j+1 , grid , n , m , dp); \n if(i+1 < n ) op3 = grid[i+1][j] - grid[i][j];\n if(j+1 < m) op4 = grid[i][j+1] - grid[i][j];\n \n return dp[i][j] = max(right , max(down , max(op3 , op4)));\n }\n\n int maxScore(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n vector<vector<int>> dp(n, vector<int>(m , -1));\n int maxi = -1e8;\n for(int i = 0 ; i < n ; i++){\n for(int j = 0 ; j < m ; j++){\n maxi = max(maxi , f(i , j , grid , n , m , dp ));\n }\n }\n return maxi;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-difference-score-in-a-grid | Grid DP🎯 | Top Down➡️Bottom Up | ✔️Multi Tabulation✔️ | 🔥Unique DP Approach | Clean Code🔥 | grid-dp-top-downbottom-up-multi-tabulati-mbpd | \uD83D\uDE0A ~ \uD835\uDE52\uD835\uDE5E\uD835\uDE69\uD835\uDE5D \u2764\uFE0F \uD835\uDE57\uD835\uDE6E \uD835\uDE43\uD835\uDE5E\uD835\uDE67\uD835\uDE5A\uD835\uDE | hirenjoshi | NORMAL | 2024-10-19T10:31:18.284102+00:00 | 2024-10-19T19:53:43.749767+00:00 | 7 | false | \uD83D\uDE0A ~ \uD835\uDE52\uD835\uDE5E\uD835\uDE69\uD835\uDE5D \u2764\uFE0F \uD835\uDE57\uD835\uDE6E \uD835\uDE43\uD835\uDE5E\uD835\uDE67\uD835\uDE5A\uD835\uDE63\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n***Hello there! Take a look at the code and comments within it you\'ll get it.\nStill have doubts? Feel free to comment, I\'ll definitely reply!***\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n***All Approach :-\n: Using Top Down (Memoization + 2D Tabulation) - TLE\n: Using Bottom Up (2D Multi Tabulation) - Accepted***\n\n# Complexity\n- ***Time complexity: Mentioned with the code***\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- ***Space complexity: Mentioned with the code***\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n**Approach 1 : Using Top Down (Memoization + 2D Tabulation) - TLE**\n```\nclass TopDown {\n int N, M;\n\n // O(M*N*M + N*N*M) & O(N*M + N+M)\n int getMaxPositiveScore(vector<vector<int>>& dp, vector<vector<int>>& grid, int startR, int startC) {\n // Memoization table: If the current state is already computed then return the comptuted value\n if(dp[startR][startC] != -1)\n return dp[startR][startC];\n\n // There are always two possibilities to perform at each cell\n int moveRight = 0; // Is to move to any right cell \n int moveDown = 0; // Is to move to any bottom cell\n\n // Explore each right cell and get the score you can get from all the possibility and then update the result by the maximum value\n for(int C = startC+1; C < M; ++C) \n moveRight = max(moveRight, grid[startR][C] - grid[startR][startC] + getMaxPositiveScore(dp, grid, startR, C));\n \n // Explore each bottom cell and get the score you can get from all the possibility and then update the result by the maximum value\n for(int R = startR+1; R < N; ++R) \n moveDown = max(moveDown, grid[R][startC] - grid[startR][startC] + getMaxPositiveScore(dp, grid, R, startC));\n\n // Store the result value to the memoization table and then return it\n return dp[startR][startC] = max(moveRight, moveDown);\n }\n // Note: Without memoization the time complexity of this function will be O(M^(N*M) + N^(N*M)) and the auxiliary space will be O(N+M)\n\n // O(3*N*M) & O(2*N*M)\n int getMaxNegativeScore(vector<vector<int>>& grid) {\n // 2D tabulation tables\n vector<vector<int>> maxElementRight(N, vector<int>(M, INT_MIN));\n vector<vector<int>> maxElementDown(N, vector<int>(M, INT_MIN));\n\n // Find the maximum element lying at the right side of each cell\n for(int R = 0; R < N; ++R) {\n maxElementRight[R][M-1] = grid[R][M-1];\n for(int C = M-2; C >= 0; --C) {\n maxElementRight[R][C] = max(grid[R][C], maxElementRight[R][C+1]);\n }\n }\n\n // Find the maximum element lying at the bottom side of each cell\n for(int C = 0; C < M; ++C) {\n maxElementDown[N-1][C] = grid[N-1][C];\n for(int R = N-2; R >= 0; --R) {\n maxElementDown[R][C] = max(grid[R][C], maxElementDown[R+1][C]);\n }\n }\n \n int maxNegScore = INT_MIN;\n\n // Move to each cell and update the maximum negative score\n for(int R = 0; R < N; ++R) {\n for(int C = 0; C < M; ++C) {\n int scoreRight = (C + 1 < M) ? maxElementRight[R][C + 1] : INT_MIN;\n int scoreDown = (R + 1 < N) ? maxElementDown[R + 1][C] : INT_MIN;\n if(scoreRight != INT_MIN) maxNegScore = max(maxNegScore, scoreRight - grid[R][C]);\n if(scoreDown != INT_MIN) maxNegScore = max(maxNegScore, scoreDown - grid[R][C]);\n }\n }\n \n return maxNegScore;\n }\n\npublic:\n // Method to find the maximum score you can achieve, using recursion with memoization and 2D tabulation - O(N*M*(M+N)) & O(N*M)\n int maxScore(vector<vector<int>>& grid) {\n N = grid.size(), M = grid[0].size();\n\n int maxPosScore = 0;\n\n // 2D memoization table\n vector<vector<int>> dp(N, vector<int>(M, -1));\n\n // Consider each cell as an unique start point and find the maximum positive score you can get from it and then update the result by the maximum value\n for(int R = 0; R < N; ++R)\n for(int C = 0; C < M; ++C)\n maxPosScore = max(maxPosScore, getMaxPositiveScore(dp, grid, R, C));\n \n // If the maximum positive score is 0 then there is a chance that the result could be a maximum negative value hence find the maximum negative score and then return it\n return (maxPosScore == 0) ? getMaxNegativeScore(grid) : maxPosScore;\n }\n};\n// Note: This solution will lead to time-limit-exceed\n```\n**Approach 2 : Using Bottom Up (2D Multi Tabulation) - Accepted**\n```\nclass BottomUp {\n int N, M;\n\n // O(3*N*M) & O(2*N*M)\n int getMaxNegativeScore(vector<vector<int>>& grid) {\n // 2D tabulation tables\n vector<vector<int>> maxElementRight(N, vector<int>(M, INT_MIN));\n vector<vector<int>> maxElementDown(N, vector<int>(M, INT_MIN));\n\n // Find the maximum element lying at the right side of each cell\n for(int R = 0; R < N; ++R) {\n maxElementRight[R][M-1] = grid[R][M-1];\n for(int C = M-2; C >= 0; --C) {\n maxElementRight[R][C] = max(grid[R][C], maxElementRight[R][C+1]);\n }\n }\n\n // Find the maximum element lying at the bottom side of each cell\n for(int C = 0; C < M; ++C) {\n maxElementDown[N-1][C] = grid[N-1][C];\n for(int R = N-2; R >= 0; --R) {\n maxElementDown[R][C] = max(grid[R][C], maxElementDown[R+1][C]);\n }\n }\n \n int maxNegScore = INT_MIN;\n\n // Move to each cell and update the maximum negative score\n for(int R = 0; R < N; ++R) {\n for(int C = 0; C < M; ++C) {\n int scoreRight = (C+1 < M) ? maxElementRight[R][C+1] : INT_MIN;\n int scoreDown = (R+1 < N) ? maxElementDown[R+1][C] : INT_MIN;\n if(scoreRight != INT_MIN) maxNegScore = max(maxNegScore, scoreRight - grid[R][C]);\n if(scoreDown != INT_MIN) maxNegScore = max(maxNegScore, scoreDown - grid[R][C]);\n }\n }\n\n return maxNegScore;\n }\n\npublic:\n // Method to find the maximum score you can achieve, using 2D multi tabulation - O(N*M*(M+N)) & O(N*M)\n int maxScore(vector<vector<int>>& grid) {\n N = grid.size(), M = grid[0].size();\n\n int maxPosScore = 0;\n\n // 2D tabulation table\n vector<vector<int>> dp(N, vector<int>(M, 0));\n\n // Fill the table and find the maximum positive score you can get\n for(int startR = N-1; startR >= 0; --startR) {\n for(int startC = M-1; startC >= 0; --startC) {\n int moveRight = 0;\n int moveDown = 0;\n\n for(int C = startC+1; C < M; ++C) \n moveRight = max(moveRight, grid[startR][C] - grid[startR][startC] + dp[startR][C]); \n for(int R = startR+1; R < N; ++R) \n moveDown = max(moveDown, grid[R][startC] - grid[startR][startC] + dp[R][startC]);\n \n dp[startR][startC] = max(moveRight, moveDown);\n maxPosScore = max(maxPosScore, dp[startR][startC]);\n }\n }\n\n // If the maximum positive score is 0 then there is a chance that the result could be a maximum negative value hence find the maximum negative score and then return it\n return (maxPosScore == 0) ? getMaxNegativeScore(grid) : maxPosScore;\n }\n};\n```\n\uD835\uDDE8\uD835\uDDE3\uD835\uDDE9\uD835\uDDE2\uD835\uDDE7\uD835\uDDD8 \uD835\uDDDC\uD835\uDDD9 \uD835\uDDEC\uD835\uDDE2\uD835\uDDE8 \uD835\uDDDF\uD835\uDDDC\uD835\uDDDE\uD835\uDDD8 \uD835\uDDE7\uD835\uDDDB\uD835\uDDD8 \uD835\uDDE6\uD835\uDDE2\uD835\uDDDF\uD835\uDDE8\uD835\uDDE7\uD835\uDDDC\uD835\uDDE2\uD835\uDDE1 \uD83D\uDC4D | 0 | 0 | ['Array', 'Dynamic Programming', 'Matrix', 'C++'] | 0 |
maximum-difference-score-in-a-grid | Iterative DP. Time: O(rowsxcols), Space: O(cols) | iterative-dp-time-orowsxcols-space-ocols-mzh5 | Approach\n Describe your approach to solving the problem. \nTraverse matrix from bottom right exploring both options for each cells - bottom or to the right. St | iitjsagar | NORMAL | 2024-10-02T07:01:15.602535+00:00 | 2024-10-02T07:01:15.602572+00:00 | 0 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nTraverse matrix from bottom right exploring both options for each cells - bottom or to the right. Store the values in a 1-d array which will be updated as we move up the rows.\n\n# Complexity\n- Time complexity: $$O(ROWSxCOLS)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(COLS)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python []\nclass Solution(object):\n def maxScore(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n """\n ROWS = len(grid)\n COLS = len(grid[0])\n col_opt = [0]*COLS\n\n res = float("-inf")\n col_opt[-1] = grid[-1][-1]\n max_so_far = grid[-1][-1]\n for c in range(COLS-2,-1,-1):\n res = max(res, max_so_far - grid[-1][c])\n col_opt[c] = max(grid[-1][c], max_so_far)\n max_so_far = max(max_so_far, grid[-1][c])\n \n\n #print col_opt\n #print res\n\n for r in range(ROWS-2,-1,-1):\n res = max(res, col_opt[-1] - grid[r][-1])\n col_opt[-1] = max(grid[r][-1],col_opt[-1])\n\n max_in_cur_col = col_opt[-1]\n\n #print "row:",r,"col:",col_opt, res, max_in_cur_col\n\n for c in range(COLS-2,-1,-1):\n res = max(res, max(col_opt[c],max_in_cur_col)- grid[r][c])\n\n #print "row:",r,"col:",col_opt, res\n\n col_opt[c] = max(grid[r][c], max(max_in_cur_col, col_opt[c]))\n\n max_in_cur_col = max(max_in_cur_col, col_opt[c])\n\n return res \n\n``` | 0 | 0 | ['Python'] | 0 |
maximum-difference-score-in-a-grid | Basics DP in Matrix || O(N^2) | basics-dp-in-matrix-on2-by-dnanper-v0ie | 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 | dnanper | NORMAL | 2024-09-25T05:20:58.860114+00:00 | 2024-09-25T05:20:58.860148+00:00 | 3 | 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```cpp []\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) \n {\n ios::sync_with_stdio(false);\n cin.tie(0);\n int res = -1e8;\n for (int i = 0; i < grid.size(); i++)\n {\n for (int j = 0; j < grid[0].size(); j++)\n {\n if (i == 0 && j == 0) continue;\n res = max(max(res,grid[i][j] - (j==0?INT_MAX:grid[i][j-1])), grid[i][j] - (i==0?INT_MAX:grid[i-1][j]));\n grid[i][j] = min(j==0?INT_MAX:grid[i][j-1], min(grid[i][j], i==0?INT_MAX:grid[i-1][j]));\n }\n cout << endl;\n }\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-difference-score-in-a-grid | Memo dp | memo-dp-by-code7you-vb39 | 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 | code7you | NORMAL | 2024-09-09T14:52:08.647813+00:00 | 2024-09-09T14:52:08.647836+00:00 | 5 | 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```java []\nclass Solution {\n private Integer dp[][];\n \n public int maxScore(List<List<Integer>> grid) {\n int m = grid.size(), n = grid.get(0).size();\n dp = new Integer[m][n];\n int max = Integer.MIN_VALUE;\n \n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n int temp = getMaxDiff(i, j, m, n, grid);\n max = Math.max(temp, max);\n }\n }\n \n return max;\n }\n \n public int getMaxDiff(int row, int col, int m, int n, List<List<Integer>> grid) {\n if (row >= m || col >= n) return Integer.MIN_VALUE;\n if (dp[row][col] != null) return dp[row][col];\n \n int max = Integer.MIN_VALUE;\n int ele = grid.get(row).get(col);\n \n if (row + 1 < m) \n max = Math.max(max, grid.get(row + 1).get(col) - ele + Math.max(0, getMaxDiff(row + 1, col, m, n, grid)));\n \n if (col + 1 < n) \n max = Math.max(max, grid.get(row).get(col + 1) - ele + Math.max(0, getMaxDiff(row, col + 1, m, n, grid)));\n \n return dp[row][col] = max;\n }\n}\n\n``` | 0 | 0 | ['Java'] | 0 |
maximum-difference-score-in-a-grid | 🔥Easy Explanation | |✅ Simple Solution | | 🧠Beginner friendly | easy-explanation-simple-solution-beginne-rg02 | \n# Approach\n1. Since we are allowed to start from any index initiate recursion call from all the indices\n2. For Every Index (i,j) There are 4 Choices.\n- Cho | Rahul_Hebbare | NORMAL | 2024-09-02T06:30:35.271892+00:00 | 2024-09-02T06:30:35.271925+00:00 | 6 | false | \n# Approach\n**1**. Since we are allowed to start from any index initiate recursion call from all the indices\n**2**. For Every Index (i,j) There are 4 Choices.\n- **Choice 1**:Move to right index `(i,j+1)` stop the further indices consideration\n- **Choice 2**:Move to right index `(i,j+1)` ,make recursive `(eg. function(i,j+1))` for further indices consideration.\n- **Choice 3**:Move to bottom index `(i+1,j)` stop the further indices consideration\n- **Choice 4**:Move to bottom index `(i+1,j)` ,make recursive `(eg. function(i+1,j))` for further indices consideration.\n**3**. Consider Max of all 4 choices\n# Complexity\n- Time complexity:\n $$O(m*n)$$ \n\n- Space complexity:\n$$O(m*n)$$ \n\n# Code\n```cpp []\nclass Solution {\n int n,m;\n int get(int i,int j,vector<vector<int>>& grid,vector<vector<long long>> &dp){\n if(i>=n || j>=m){\n return 0;\n }\n\n if(dp[i][j]!=LLONG_MAX){\n return dp[i][j];\n }\n long long right=INT_MIN,bottom=INT_MIN;\n long long a=INT_MIN,b=INT_MIN;\n\n if(j+1<m){\n a=(grid[i][j+1]-grid[i][j]);//Choice 1\n right=a+get(i,j+1,grid,dp);//Choice 2\n }\n if(i+1<n){\n b=(grid[i+1][j]-grid[i][j]);//Choice 3\n bottom=b+get(i+1,j,grid,dp);//Choice 3\n }\n return dp[i][j]=max(a,max(b,max(right,bottom)));\n }\npublic:\n int maxScore(vector<vector<int>>& grid) {\n n=grid.size(),m=grid[0].size();\n int maxi=INT_MIN;\n vector<vector<long long>> dp(n,vector<long long>(m,LLONG_MAX));\n \n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n maxi=max(maxi,get(i,j,grid,dp));\n }\n }\n return maxi;\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'Backtracking', 'C++'] | 0 |
maximum-difference-score-in-a-grid | Simple C++ solution | simple-c-solution-by-cyphermain-vt02 | Intuition\n Describe your first thoughts on how to solve this problem. \nTry to find the highest range in every possible sub-matrix / sub-problem.\n# Approach\n | cyphermain | NORMAL | 2024-08-22T11:17:36.267807+00:00 | 2024-08-22T11:17:36.267839+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTry to find the highest range in every possible sub-matrix / sub-problem.\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```cpp []\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int res = INT_MIN;\n\n for(int i=0;i<grid.size(); i++){\n for(int j=0;j<grid[0].size(); j++){\n int localRange = INT_MIN;\n if( i-1>=0 && j-1>=0 ){\n localRange = grid[i][j] - min(grid[i-1][j], grid[i][j-1]);\n grid[i][j] = min( grid[i][j], min(grid[i-1][j], grid[i][j-1]) );\n }else if(i-1>=0){\n localRange = grid[i][j] - grid[i-1][j] ;\n grid[i][j] = min( grid[i][j], grid[i-1][j] );\n } else if(j-1>=0){\n localRange = grid[i][j] - grid[i][j-1] ;\n grid[i][j] = min( grid[i][j], grid[i][j-1] );\n }\n res = max(res, localRange);\n }\n }\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-difference-score-in-a-grid | python beats 22.58 percent | python-beats-2258-percent-by-snah0902-k6lb | Code\npython3 []\nclass Solution:\n def maxScore(self, grid: List[List[int]]) -> int:\n \n rows = len(grid)\n cols = len(grid[0])\n | snah0902 | NORMAL | 2024-08-20T06:52:06.165534+00:00 | 2024-08-20T06:52:06.165558+00:00 | 12 | false | # Code\n```python3 []\nclass Solution:\n def maxScore(self, grid: List[List[int]]) -> int:\n \n rows = len(grid)\n cols = len(grid[0])\n largestMax = [[0 for _ in range(cols)] for _ in range(rows)]\n\n @cache\n def findMax(row, col):\n if row >= rows or col >= cols:\n return -int(1E9)\n largestMax[row][col] = max(findMax(row + 1, col), findMax(row, col + 1))\n return max(grid[row][col], largestMax[row][col])\n\n findMax(0, 0)\n res = -int(1E9)\n for row in range(rows):\n for col in range(cols):\n res = max(res, largestMax[row][col] - grid[row][col])\n return res\n``` | 0 | 0 | ['Python3'] | 0 |
maximum-difference-score-in-a-grid | ✅Easy and Simple Solution ✅Clean Code | easy-and-simple-solution-clean-code-by-a-9r15 | Guy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F\nFoll | ayushluthra62 | NORMAL | 2024-08-15T15:34:36.050953+00:00 | 2024-08-15T15:34:36.051011+00:00 | 6 | false | ***Guy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F***<br>\n**Follow me on LinkeDin [[click Here](https://www.linkedin.com/in/ayushluthra62/)]**\n\n# Complexity\n- Time complexity:\nO( N * M)\n\n- Space complexity:\nO(N * M)\n\n# Code\n```\nclass Solution {\npublic:\n int solve(vector<vector<int>>& grid, int currI , int currJ , int n , int m,vector<vector<int>>&dp){\n if(currI >= n || currJ >= m) return 0 ;\n \n if(dp[currI][currJ] !=-1) return dp[currI][currJ];\n \n \n int maxi1 = INT_MIN;\n int maxi2 = INT_MIN;\n\n if(currI + 1 < n) maxi1 = grid[currI+1][currJ] - grid[currI][currJ] + solve(grid,currI+1,currJ,n,m,dp);\n if(currJ + 1 < m) maxi2 = grid[currI][currJ+1] - grid[currI][currJ] + solve(grid,currI,currJ+1 , n, m,dp);\n\n return dp[currI][currJ] = max(0,max(maxi1,maxi2));\n\n \n }\n int maxScore(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n int ans = INT_MIN;\n int ans2 = INT_MIN;\n vector<vector<int>>dp(n,vector<int>(m,-1));\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n \n \n ans = max(ans, solve(grid,i,j,n,m,dp));\n if(i+1 < n) ans2 = max(ans2,grid[i+1][j] - grid[i][j]);\n if(j+1 < m) ans2 = max(ans2,grid[i][j+1] - grid[i][j]);\n \n }\n }\n\n return ans == 0 ? ans2 : ans;\n }\n};\n```\n***Guy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F***<br>\n**Follow me on LinkeDin [[click Here](https://www.linkedin.com/in/ayushluthra62/)]** | 0 | 0 | ['Array', 'Dynamic Programming', 'Matrix', 'C++'] | 0 |
maximum-difference-score-in-a-grid | Easy to Understand || Dynamic Programming || Two - Approaches || C++ | easy-to-understand-dynamic-programming-t-d8vf | 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 | ksohelkhan064 | NORMAL | 2024-08-10T20:48:36.716292+00:00 | 2024-08-10T20:48:36.716318+00:00 | 16 | 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```\nclass Solution {\npublic:\n\n int solve(int i, int j, int &mx, vector<vector<int>>& grid, vector<vector<int>>& dp) {\n int n = grid.size(); // Number of rows in the grid\n int m = grid[0].size(); // Number of columns in the grid\n\n // Base case: if out of bounds, return a very small number to indicate invalid path\n if (i >= n || j >= m) return -1e8;\n\n // Return the precomputed result if it exists in the dp table\n if (dp[i][j] != -1) return dp[i][j];\n\n // Recursive call to explore the path moving downward\n int bottom = solve(i + 1, j, mx, grid, dp);\n\n // Recursive call to explore the path moving rightward\n int right = solve(i, j + 1, mx, grid, dp);\n\n // Determine the maximum cell value that can be obtained from either moving downward or rightward\n int maxi = max(bottom, right);\n\n // Update the ans \'mx\' found so far by considering the current cell\n mx = max(mx, maxi - grid[i][j]);\n\n // Store and return the maximum value of the current cell \n return dp[i][j] = max(maxi, grid[i][j]);\n}\n\n int maxScore(vector<vector<int>>& grid) {\n \n\n // Approach - 01\n\n int n = grid.size(); \n int m = grid[0].size(); \n\n int mx = -1e8;\n vector<vector<int>>dp(n,vector<int>(m,-1));\n solve(0,0,mx,grid,dp);\n return mx;\n \n \n\n\n // Approach - 02\n\n int ans = INT_MIN; // Initialize the maximum score to the smallest possible integer\n\n // Iterate through each cell in the grid\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < m; j++) {\n int mini = INT_MAX; // Initialize mini to the largest possible integer\n\n // Skip the top-left cell (0,0) as it has no previous cell to compare\n if(i == 0 && j == 0) continue;\n\n // Update mini with the minimum value from the cell directly above\n if(i != 0) mini = min(mini, grid[i-1][j]);\n\n // Update mini with the minimum value from the cell directly to the left\n if(j != 0) mini = min(mini, grid[i][j-1]);\n\n // Compute the score for the current cell and update the maximum score found so far\n ans = max(ans, grid[i][j] - mini);\n\n // Update the current cell value in the grid to be the minimum of itself and the mini value found\n grid[i][j] = min(mini, grid[i][j]);\n }\n }\n\n \n // return ans;\n\n \n }\n};\n\n``` | 0 | 0 | ['Array', 'Dynamic Programming', 'Recursion', 'Memoization', 'Matrix', 'C++'] | 0 |
maximum-difference-score-in-a-grid | Java || Memoization || O(N*N) | java-memoization-onn-by-gar1266doda-ah2x | 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 | gar1266doda | NORMAL | 2024-08-02T18:07:00.463208+00:00 | 2024-08-02T18:07:00.463238+00:00 | 2 | 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```\nclass Solution {\n int res=Integer.MIN_VALUE;\n public int find(int i, int j, List<List<Integer>> grid, int n, int m, int dp[][]){\n if(i==n-1&&j==m-1) return 0;\n if(dp[i][j]!=Integer.MIN_VALUE) return dp[i][j];\n int max=Integer.MIN_VALUE;\n if(i<n-1){\n max=Math.max(max,grid.get(i+1).get(j)-grid.get(i).get(j)+Math.max(0,find(i+1,j,grid,n,m,dp)));\n }\n if(j<m-1){\n max=Math.max(max,grid.get(i).get(j+1)-grid.get(i).get(j)+Math.max(0,find(i,j+1,grid,n,m,dp)));\n }\n dp[i][j]=max;\n res=Math.max(res,dp[i][j]);\n return dp[i][j];\n }\n public int maxScore(List<List<Integer>> grid) {\n int n=grid.size();\n int m=grid.get(0).size();\n int dp[][]=new int[n+1][m+1];\n for(int i=0;i<=n;i++){\n for(int j=0;j<=m;j++) dp[i][j]=Integer.MIN_VALUE;\n }\n find(0,0,grid,n,m,dp);\n return res;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
maximum-difference-score-in-a-grid | ugly mutable scala solution to avoid MLE | ugly-mutable-scala-solution-to-avoid-mle-cjor | \nobject Solution {\n val arr = Array.fill(1001,1001)(0)\n def maxScore(grid: List[List[Int]]): Int =\n var i: Int = 0; var j: Int = 0\n arr(0)(0) = gri | vititov | NORMAL | 2024-07-15T22:27:10.946851+00:00 | 2024-07-15T22:27:10.946882+00:00 | 4 | false | ```\nobject Solution {\n val arr = Array.fill(1001,1001)(0)\n def maxScore(grid: List[List[Int]]): Int =\n var i: Int = 0; var j: Int = 0\n arr(0)(0) = grid(0)(0)\n var ans = Int.MinValue\n i = 1; while (i<grid.length) {\n arr(i)(0) = arr(i-1)(0) min grid(i)(0); ans = ans max (grid(i)(0) - arr(i-1)(0)); i+=1\n }\n j = 1; while (j<grid.head.length) {\n arr(0)(j) = arr(0)(j-1) min grid(0)(j); ans = ans max (grid(0)(j) - arr(0)(j-1)); j+=1\n }\n i=1; while (i<grid.length) {\n j=1; while (j<grid.head.length) {\n arr(i)(j) = arr(i-1)(j) min arr(i)(j-1) min grid(i)(j)\n ans = ans max (grid(i)(j) - (arr(i-1)(j) min arr(i)(j-1)))\n j+=1\n }\n i+=1\n }\n ans\n\n def maxScore1(grid: List[List[Int]]): Int =\n val x1 = grid.map(_.scanLeft(Int.MaxValue)(_ min _).drop(1)).transpose\n .map(_.scanLeft(Int.MaxValue)(_ min _).drop(1)).transpose\n def getX1(i: Int)(j: Int):Option[Int] = \n Option.when(i>=0 && i<grid.length && j>=0 && j<grid.head.length) {x1(i)(j)}\n val x2 = (grid.toList.flatten zip x1.toList.flatten).map{case (a,b) => a-b}.max\n val x3 = (for{i <- grid.indices; j <-grid.head.indices} yield { (i,j)})\n .flatMap{case (i,j) =>\n List(getX1(i-1)(j), getX1(i)(j-1)).flatten.map{case v => grid(i)(j) - v}\n }.max\n x3\n}\n``` | 0 | 0 | ['Matrix', 'Scala'] | 0 |
maximum-difference-score-in-a-grid | Easy Iterative Dp Solution | easy-iterative-dp-solution-by-kvivekcode-vxia | 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 | kvivekcodes | NORMAL | 2024-07-09T06:26:44.002895+00:00 | 2024-07-09T06:26:44.002930+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```\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int ans = INT_MIN;\n int n = grid.size(), m = grid[0].size();\n vector<vector<int> > dp(n, vector<int> (m, -1e8));\n for(int i = 0; i < n; i++){\n for(int j = 0; j < m; j++){\n // come from left\n for(int k = 0; k < j; k++){\n dp[i][j] = max(dp[i][j], ((dp[i][k] == -1e8) ? 0 : max(0, dp[i][k])) + grid[i][j]-grid[i][k]);\n }\n // come from top\n for(int k = 0; k < i; k++){\n dp[i][j] = max(dp[i][j], ((dp[k][j] == -1e8) ? 0 : max(0, dp[k][j])) + grid[i][j]-grid[k][j]);\n }\n ans = max(ans, dp[i][j]);\n }\n }\n\n return ans;\n }\n};\n``` | 0 | 0 | ['Array', 'Dynamic Programming', 'Matrix', 'C++'] | 0 |
maximum-difference-score-in-a-grid | Beats 99.85% C++ Solution | beats-9985-c-solution-by-su47-vk0n | Intuition\nFinfing min upto index i,j and reducing it from grid[i][j] and iterating to find max out of all such differences \n\n# Approach\nIterate from 0,0 to | su47 | NORMAL | 2024-07-02T18:00:40.841722+00:00 | 2024-07-02T18:00:40.841745+00:00 | 1 | false | # Intuition\nFinfing min upto index i,j and reducing it from grid[i][j] and iterating to find max out of all such differences \n\n# Approach\nIterate from 0,0 to i,j notice upto this point all i-1,j and i,j-1 had been already calculated so can esily use them\nso\n minval(i,j) = min( minval( i-1 , j ), minval( i, j-1 ))\nwhere minval(i,j) represents minvalue upto i,j\n# Complexity\n- Time complexity:\n$$O(n*m)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nint speedup = []{ios::sync_with_stdio(0); cin.tie(0); return 0;}();\nclass Solution {\n\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int ans = INT_MIN;\n for(int i = 0; i < grid.size(); ++i){\n for(int j = 0; j < grid[0].size(); ++j){\n int mn = INT_MAX;\n if(i == 0 && j == 0) continue;\n if(i != 0) mn = min(mn, grid[i-1][j]);\n if(j != 0) mn = min(mn, grid[i][j-1]);\n ans = max(ans, grid[i][j] - mn);\n grid[i][j] = min(grid[i][j], mn);\n }\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-difference-score-in-a-grid | c++ || tabular dp || O(m*n) | c-tabular-dp-omn-by-sarthakrautelanew-91fq | 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 | sarthakrautelanew | NORMAL | 2024-06-30T09:19:38.481433+00:00 | 2024-06-30T09:19:38.481458+00:00 | 8 | 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)$$ -->\nO(n*m)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n*m)\n# Code\n```\nclass Solution {\npublic:\n \n int maxScore(vector<vector<int>>& grid) {\n int n=grid.size();\n int m=grid[0].size();\n\n vector<vector<int>>dp(n,vector<int>(m,-1e6));\n vector<int>row(n,-1e6),col(m,-1e6);\n row[0]=-grid[0][0];\n col[0]=-grid[0][0];\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n \n if(i==0 && j==0)\n continue;\n\n dp[i][j]= max(grid[i][j]+col[j],dp[i][j]);\n\n col[j]=max(col[j],-grid[i][j] + (dp[i][j]>0 ?dp[i][j] :0 ));\n\n \n dp[i][j]= max(grid[i][j]+row[i],dp[i][j]);\n\n row[i]=max(row[i],-grid[i][j] + (dp[i][j]>0 ?dp[i][j] :0 ));\n \n }\n }\n int ans=-1e8;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(i==0 && j==0)\n continue;\n ans=max(dp[i][j],ans);\n }\n }\n \nreturn ans;\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'Memoization', 'C++'] | 0 |
maximum-difference-score-in-a-grid | Explained the approach || DP solution | explained-the-approach-dp-solution-by-ar-fp6j | Intuition\nmax(c2-c1)=>c2 should be maximum and c1 should be minimum\n# Approach\nApproach written in the code in form of comments:)\n# Complexity\n- Time comp | arsalan21 | NORMAL | 2024-06-28T13:29:41.244831+00:00 | 2024-06-28T13:30:32.664925+00:00 | 10 | false | # Intuition\nmax(c2-c1)=>c2 should be maximum and c1 should be minimum\n# Approach\nApproach written in the code in form of comments:)\n# Complexity\n- Time complexity:\nO(n*m)\n- Space complexity:\nO(n*m)\n# Code\n```\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int n=grid.size(),m=grid[0].size();\n int max_ans=-1e9;\n vector<vector<int>>dp(n,vector<int>(m,1e9));\n dp[0][0]=grid[0][0];\n //initialise the min value for zeroth row and col\n for(int i=1;i<m;i++){\n dp[0][i]=min(dp[0][i-1],grid[0][i]);\n }\n for(int j=1;j<n;j++){\n dp[j][0]=min(dp[j-1][0],grid[j][0]);\n }\n //(c2-c1) to be maximum c2 should be maximum and c1 should be minimum\n //get the minimum of points for each grid\n for(int i=1;i<n;i++){\n for(int j=1;j<m;j++){\n //since we can move right and bottom\n dp[i][j]=min(dp[i-1][j],dp[i][j-1]);\n //if grid[i][j] itself is the min\n dp[i][j]=min(dp[i][j],grid[i][j]);\n }\n }\n // to get the maximum score we can subtract each value of grid to min(just above,just left)\n //and take the maximum of all the values\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(j>0)\n max_ans=max(max_ans,grid[i][j]-dp[i][j-1]);\n if(i>0)\n max_ans=max(max_ans,grid[i][j]-dp[i-1][j]);\n }\n }\n return max_ans;\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'Matrix', 'C++'] | 0 |
maximum-difference-score-in-a-grid | Submatrix max minus current corner | submatrix-max-minus-current-corner-by-su-v72b | Complexity\n- Time complexity: O(mn)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(mn)\n Add your space complexity here, e.g. O(n) \n\n# | Sukhvansh2004 | NORMAL | 2024-06-26T16:07:45.465012+00:00 | 2024-06-26T16:07:45.465055+00:00 | 1 | false | # Complexity\n- Time complexity: $$O(mn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(mn)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int m;\n int n;\n\n void recurse(vector<vector<int>>& dp, vector<vector<int>>& grid, int& res,\n int i, int j) {\n if (i >= m || j >= n) {\n return;\n }\n\n if (dp[i][j] != -1) {\n return;\n }\n\n int rightValue = INT_MIN, downValue = INT_MIN;\n if (j + 1 < n) {\n recurse(dp, grid, res, i, j + 1);\n rightValue = dp[i][j + 1];\n }\n\n if (i + 1 < m) {\n recurse(dp, grid, res, i + 1, j);\n downValue = dp[i + 1][j];\n }\n\n if (i == m - 1 && j == n - 1) {\n dp[i][j] = grid[i][j];\n } else {\n dp[i][j] = max(grid[i][j], max(rightValue, downValue));\n res = max(res, max(rightValue, downValue) - grid[i][j]);\n } \n }\n\n int maxScore(vector<vector<int>>& grid) {\n m = grid.size();\n n = grid[0].size();\n vector<vector<int>> dp(m, vector<int>(n, -1));\n int res = INT_MIN;\n recurse(dp, grid, res, 0, 0);\n return res;\n }\n};\n\n``` | 0 | 0 | ['C++'] | 0 |
maximum-difference-score-in-a-grid | DP | dp-by-karandumdumguy-yfbw | 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 | karandumdumguy | NORMAL | 2024-06-22T14:21:54.688800+00:00 | 2024-06-22T14:21:54.688827+00:00 | 5 | 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: O(mxn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(mxn)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int ans = INT_MIN;\n int m = grid.size();\n int n = grid[0].size();\n vector<vector<int>> dp(m, vector<int>(n, INT_MIN));\n dp[0][0] = 0;\n \n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (i == 0 && j == 0)\n continue;\n // left\n if (j - 1 >= 0) {\n int c2 = grid[i][j];\n int c1 = grid[i][j-1];\n int optimalPathFromLeft = dp[i][j-1];\n\n dp[i][j] = max(dp[i][j], max(c2 - c1, c2 - c1 + optimalPathFromLeft));\n }\n\n // upwards\n if (i - 1 >= 0) {\n int c2 = grid[i][j];\n int c1 = grid[i-1][j];\n int optimalPathFromUp = dp[i-1][j];\n\n dp[i][j] = max(dp[i][j], max(c2 - c1, c2 - c1 + optimalPathFromUp));\n }\n ans = max(ans, dp[i][j]);\n }\n }\n return ans;\n }\n};\n\n``` | 0 | 0 | ['Dynamic Programming', 'Matrix', 'C++'] | 0 |
maximum-difference-score-in-a-grid | Brute Force DP with optimised solution with comments and Intution | brute-force-dp-with-optimised-solution-w-kq7q | Brute Force Solution(TLE)\nHere dp[i][j]-> It tells we have maximum score we can get if we consider from (i,j) to (n-1,m-1)\n\nclass Solution {\npublic:\n us | vaibhav2304 | NORMAL | 2024-06-22T05:10:44.171921+00:00 | 2024-06-22T05:11:46.490178+00:00 | 3 | false | * Brute Force Solution(TLE)\nHere dp[i][j]-> It tells we have maximum score we can get if we consider from (i,j) to (n-1,m-1)\n```\nclass Solution {\npublic:\n using v1d = vector<int>;\n using v2d = vector<v1d>;\n int maxScore(vector<vector<int>>& grid) {\n int n=grid.size(),m=grid[0].size();\n v2d dp(n,v1d(m,-1e9));\n for(int i=n-1;i>=0;i--){\n for(int j=m-1;j>=0;j--){\n for(int newi=i+1;newi<n;newi++){\n dp[i][j]=max(dp[i][j],grid[newi][j]-grid[i][j]);\n dp[i][j]=max(dp[i][j],grid[newi][j]-grid[i][j]+dp[newi][j]);\n }\n for(int newj=j+1;newj<m;newj++){\n dp[i][j]=max(dp[i][j],grid[i][newj]-grid[i][j]);\n dp[i][j]=max(dp[i][j],grid[i][newj]-grid[i][j]+dp[i][newj]);\n }\n }\n }\n int res=-1e9;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n res=max(res,dp[i][j]);\n }\n }\n return res;\n }\n};\n\n```\n\n* Optimised solution using min top-left \n* 1. Observation here: (a-b) + (c-b) + ....... = last element taken - first element taken.\n* All other things cancel out and they are redundant to consider\n```\nclass Solution {\npublic:\n using v1d = vector<int>;\n using v2d = vector<v1d>;\n int maxScore(vector<vector<int>>& grid) {\n int n=grid.size(),m=grid[0].size();\n v2d dp(n,v1d(m,1e9));\n //dp[i][j] -> Minimum element in the top left column\n //Transition -> Have to update dp[i][j],res\n int res=-1e9;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(i>0) dp[i][j]=min(dp[i][j],dp[i-1][j]);\n if(j>0) dp[i][j]=min(dp[i][j],dp[i][j-1]);\n res=max(res,grid[i][j]-dp[i][j]);\n dp[i][j]=min(dp[i][j],grid[i][j]);\n }\n }\n return res;\n }\n};\n```\n\nThis solution can be further optimides without using extra space of dp. It can be done by using grid as out dp array | 0 | 0 | ['Dynamic Programming', 'C'] | 0 |
maximum-difference-score-in-a-grid | Dynamic Programming --- C++ | dynamic-programming-c-by-treerecursion-t5yl | Intuition\nOptimal Substructure - Dynamic Programming (DP)\n\n# Approach\nDP (bottom up)\n\nGiven grid[i][j] as a matrix, starting from any cell at $(i, j)$, le | treerecursion | NORMAL | 2024-06-20T13:41:25.319427+00:00 | 2024-06-20T13:41:25.319461+00:00 | 1 | false | # Intuition\nOptimal Substructure - Dynamic Programming (DP)\n\n# Approach\nDP (bottom up)\n\nGiven `grid[i][j]` as a matrix, starting from any cell at $(i, j)$, let `dp[i][j]` cache the maximum score attainable. We need to consider all other cells $(i\', j\')$ if any, with $i\'> i, j\'=j$ (downwards) and $i\'=i, j\'>j$ (to the right), to optimize the score as follows.\n\n`dp[i][j] = max( grid[i\'][j\'] - grid[i][j] + max(dp[i\'][j\'], 0) )`\n\nWithin the outer `max`, the first two terms correspond to the score of moving from $(i,j)$ to $(i\', j\')$, and the inner `max` prevent further moves starting from $(i\',j\')$, if doing so only generates a negative score at the best.\n\nRegroup the terms:\n`dp[i][j] = max( grid[i\'][j\'] + max(dp[i\'][j\'], 0) ) - grid[i][j]`,\nwhere `grid[i][j]` is extracted out of the outer `max`, as it does not depend on $i\'$ or $j\'$. \n\nWe may use an `aux` matrix to cache the maxima, `max( grid[i\'][j\'] + max(dp[i\'][j\'], 0) )`, for each cell, by considering all available cells downwards or rightwards. It serves to improve time complexity, and is updated each time we compute a maximal score for a new cell.\n\n# Complexity\n- Time complexity:\nO(m*n)\n\n- Space complexity:\nO(m*n)\n\n# Code\n```\nclass Solution {\npublic:\n Solution() {ios_base::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);}\n\n int maxScore(vector<vector<int>>& grid) {\n const int m = grid.size();\n const int n = grid[0].size();\n vector<vector<int>> dp(m, vector<int>(n, 0));\n vector<vector<int>> aux(m, vector<int>(n, 0));\n aux[m-1][n-1] = grid[m-1][n-1];\n int ans{INT_MIN};\n for (int i = m-2; i >= 0; --i) {\n dp[i][n-1] = aux[i+1][n-1] - grid[i][n-1];\n aux[i][n-1] = max(aux[i+1][n-1], grid[i][n-1] + max(dp[i][n-1], 0));\n ans = max(ans, dp[i][n-1]);\n }\n for (int j = n-2; j >= 0; --j) {\n dp[m-1][j] = aux[m-1][j+1] - grid[m-1][j];\n aux[m-1][j] = max(aux[m-1][j+1], grid[m-1][j] + max(dp[m-1][j], 0));\n ans = max(ans, dp[m-1][j]);\n }\n for (int i = m-2; i >= 0; --i) {\n for (int j = n-2; j >= 0; --j) {\n dp[i][j] = max(aux[i][j+1], aux[i+1][j]) - grid[i][j];\n aux[i][j] = max({aux[i][j+1], aux[i+1][j], grid[i][j] + max(dp[i][j], 0)});\n ans = max(ans, dp[i][j]);\n }\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-difference-score-in-a-grid | [C++] DP | c-dp-by-ericyxing-xmp4 | Intuition\nFor each element $grid[i][j]$, find the smallest element on the top-left of it.\n\n# Code\n\nclass Solution {\npublic:\n int maxScore(vector<vecto | EricYXing | NORMAL | 2024-06-17T19:42:23.967194+00:00 | 2024-06-17T19:45:12.981588+00:00 | 6 | false | # Intuition\nFor each element $grid[i][j]$, find the smallest element on the top-left of it.\n\n# Code\n```\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size(), ans = INT_MIN;\n vector<int> dp(n, INT_MAX);\n dp[0] = grid[0][0];\n for (int j = 1; j < n; j++)\n {\n ans = max(ans, grid[0][j] - dp[j - 1]);\n dp[j] = min(dp[j - 1], grid[0][j]);\n }\n for (int i = 1; i < m; i++)\n {\n int minr = grid[i][0];\n ans = max(ans, grid[i][0] - dp[0]);\n dp[0] = min(dp[0], grid[i][0]);\n for (int j = 1; j < n; j++)\n {\n ans = max(ans, grid[i][j] - min(dp[j], minr));\n minr = min(minr, grid[i][j]);\n dp[j] = min(dp[j], minr);\n }\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'C++'] | 0 |
maximum-difference-score-in-a-grid | Swift | Dynamic Programming | swift-dynamic-programming-by-pagafan7as-jexd | The main idea is that the score depends only on the starting and ending cells and not on the specific path.\n\nThis observation allows us to compute the max sco | pagafan7as | NORMAL | 2024-06-16T01:18:16.282520+00:00 | 2024-06-16T01:18:16.282539+00:00 | 1 | false | The main idea is that the score depends only on the starting and ending cells and not on the specific path.\n\nThis observation allows us to compute the max score in linear time using dynamic programming.\n\n# Code\n```\nclass Solution {\n func maxScore(_ grid: [[Int]]) -> Int {\n let (m, n) = (grid.count, grid.first?.count ?? 0)\n\n // For each cell, compute the min value to its left, above or in the first\n // quadrant.\n var mins = Array(repeating: Array(repeating: 0, count: n), count: m)\n for row in 0..<m {\n for col in 0..<n {\n var minValue = Int.max\n if row > 0 { minValue = min(minValue, grid[row - 1][col], mins[row - 1][col]) }\n if col > 0 { minValue = min(minValue, grid[row][col - 1], mins[row][col - 1]) }\n\n mins[row][col] = minValue\n }\n }\n\n // For each cell, compute the score from the min value to the cell.\n var res = Int.min\n for row in 0..<m {\n for col in 0..<n {\n res = max(res, grid[row][col] - mins[row][col])\n }\n }\n return res\n }\n}\n``` | 0 | 0 | ['Swift'] | 0 |
maximum-difference-score-in-a-grid | C++ solution #intution_simpleAF | c-solution-intution_simpleaf-by-chen_ayr-ret0 | Intuition\nWe can see that we can only move down and right, and taking as many jumps in between, for a certain start and certain end, it doesn\'t matter what pa | Chen_ayr | NORMAL | 2024-06-06T03:34:00.967402+00:00 | 2024-06-06T03:34:00.967434+00:00 | 3 | false | # Intuition\nWe can see that we can only move down and right, and taking as many jumps in between, for a certain start and certain end, it doesn\'t matter what path we take, the final score will be the same.\n\n# Approach\nI make another grid named matrix where we store at any index(i,j), the maximum in the sub-grid(n,m), where i<=n<=grid.size() and j<=m<=grid[0].size(). We can make that happen but iterating in turns, like firstly, for point (i,j)\n1. We move from (i->0 to n-1) and in the nested loop we move (j->m-1 to 0) and carry the maximum to (i,0). We do it till i==0.\n\n2. Now we move from (j->m-1 to 0) and in the nested loop we move(i->n-1 to 0), we carry maximum to the top (0,j). we do it till j==0.\n\nNote that we move the iterator in the direction from right to left for each row and then from bottom to top in each column.\n\nNow, we carry out the calculation for maximum score i.e. for any index(i,j) the maximum score will be [matrix[i][j] - grid[i][j]]. And we iterate over the whole range to find the max score. If the score is 0, then we can see that either all the values are equal or they are in decreasing order in all sequences from (left to right) and (top to bottom). Then we use the difference between adjacent elements and find the maximum diff as the ans.\n\nP.S. implementation is tough, the overall thought process is simple.\n\n# Complexity\n- Time complexity:\nIt would be O(N*M) which is same to traverse the grid.\n\n- Space complexity:\nIt is O(N*M) as we are using another grid to store the maximum in any sub-grid.\n\n# Code\n```\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n vector<vector<int>> matrix;\n for (int j = 0; j < grid.size(); j++)\n {\n vector<int> vp = grid[j];\n int r = vp[vp.size() - 1];\n for (int p = vp.size() - 2; p >= 0; p--)\n {\n if (vp[p] < r)\n {\n vp[p] = r;\n }\n else\n {\n r = vp[p];\n }\n }\n matrix.push_back(vp);\n }\n for (int j = grid[0].size() - 1; j >= 0; j--)\n {\n int r = matrix[matrix.size() - 1][j];\n for (int k = grid.size() - 2; k >= 0; k--)\n {\n if (matrix[k][j] < r)\n {\n matrix[k][j] = r;\n }\n else\n {\n r = matrix[k][j];\n }\n }\n }\n int ml = INT_MIN;\n for (int i = 0; i < grid.size(); i++)\n {\n for (int j = 0; j < grid[0].size(); j++)\n {\n ml = max(ml, matrix[i][j] - grid[i][j]);\n }\n }\n if (ml == 0)\n {\n int mk = INT_MIN;\n for (int j = 0; j < grid.size(); j++)\n {\n for (int k = 1; k < grid[0].size(); k++)\n {\n mk = max(grid[j][k] - grid[j][k - 1], mk);\n }\n }\n for (int j = grid[0].size() - 1; j >= 0; j--)\n {\n for (int k = grid.size() - 1; k > 0; k--)\n {\n mk = max(mk, grid[k][j] - grid[k - 1][j]);\n }\n }\n return mk;\n }\n else\n {\n return ml;\n }\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-difference-score-in-a-grid | C++ Simple Solution | Track previous minimum. | c-simple-solution-track-previous-minimum-w23m | Intuition\nFind the minimum element from indices (0,0) to (i, j) where index (i, j)is not included. Then, take the difference of current cell with the current m | deepakchaurasiya | NORMAL | 2024-06-01T17:04:05.678867+00:00 | 2024-06-01T17:04:05.678895+00:00 | 11 | false | # Intuition\nFind the minimum element from indices (0,0) to (i, j) where index (i, j)is not included. Then, take the difference of current cell with the current minimum value.\n i.e. ans = max(ans, grid[i][j] - prev_min[i][j]);\n\n# Complexity\n- Time complexity:\nO(m*n)\n\n- Space complexity: \nO(m*n)\n\n# Code\n```\nclass Solution {\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n int ans = INT_MIN;\n \n // prev_min[i][j] contains the minimum of all elements from indices (0,0) to { (i, j-1), (i-1, j) }\n vector<vector<int>> prev_min(m, vector<int>(n, INT_MAX)); \n \n for(int i=0; i<m; i++){\n for(int j=0; j<n; j++){\n if(i==0 && j==0) continue;\n if(i>0){\n prev_min[i][j] = min(prev_min[i-1][j], grid[i-1][j]);\n }\n if(j>0){\n prev_min[i][j] = min(prev_min[i][j], min(prev_min[i][j-1], grid[i][j-1]) );\n }\n ans = max(ans, grid[i][j] - prev_min[i][j]);\n }\n }\n return ans;\n \n \n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-difference-score-in-a-grid | DP SOLUTION(tabulation) | dp-solutiontabulation-by-nithi_0805-o89n | 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 | Nithi_0805 | NORMAL | 2024-05-31T14:43:55.155294+00:00 | 2024-05-31T14:43:55.155317+00:00 | 8 | 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```\nclass Solution {\n public int maxScore(List<List<Integer>> grid) {\n int[][] ques=new int[grid.size()][grid.get(0).size()];\n for(int i=0;i<grid.size();i++)\n {\n for(int j=0;j<grid.get(0).size();j++)\n {\n ques[i][j]=grid.get(i).get(j);\n }\n }\n int[][] dp=new int[ques.length][ques[0].length];\n\n \n for(int i=ques.length-1;i>=0;i--)\n {\n for(int j=ques[0].length-1;j>=0;j--)\n {\n if(i==ques.length-1 && j==ques[0].length-1)\n {\n dp[ques.length-1][ques[0].length-1]=0;\n }\n\n \n else\n {\n int max=Integer.MIN_VALUE;\n for(int k=i,l=j+1;l<ques[0].length;l++)\n {\n max=Math.max(max,(ques[k][l]-ques[i][j]));\n max=Math.max(max,dp[k][l]+(ques[k][l]-ques[i][j]));\n }\n\n for(int l=j,k=i+1;k<ques.length;k++)\n {\n max=Math.max(max,(ques[k][l]-ques[i][j]));\n max=Math.max(max,dp[k][l]+(ques[k][l]-ques[i][j]));\n } \n dp[i][j]=max;\n } \n } \n }\n\n int ans=Integer.MIN_VALUE;\n for(int i=0;i<dp.length;i++)\n {\n for(int j=0;j<dp[0].length;j++)\n { if(i==ques.length-1 && j==ques[0].length-1)\n {\n break;\n }\n ans=Math.max(ans,dp[i][j]);\n }\n }\n\n return ans;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
maximum-difference-score-in-a-grid | DP 10ms - Java O(M*N) | O(M*N) | dp-10ms-java-omn-omn-by-wangcai20-qj2e | Intuition\n Describe your first thoughts on how to solve this problem. \nDP 2D matrix to track max score of every cell can get from top and left. Along the way, | wangcai20 | NORMAL | 2024-05-30T20:31:22.418624+00:00 | 2024-05-30T20:31:22.418649+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDP 2D matrix to track max score of every cell can get from top and left. Along the way, collect the global max and min for return.\n```\ndp[i][j] = max(0, dp[i - 1][j] + (mat[i][j] - mat[i - 1][j]), dp[i][j - 1] + (mat[i][j] - mat[i][j - 1]))\n```\n\nNote: in the case that global max is `0`, it still requires to make at leat one move. But there is no higher value cell to move to since the global max is `0`, this means we have to move to the cell with closest equal or lower value. This is why we tracks the global min too.\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```\nclass Solution {\n public int maxScore(List<List<Integer>> grid) {\n // DP: 2d - dp[i][j] = max(dp[i-1][j],dp[i][j-1],0)\n // also if the dp[i][j] is 0, update the min in case the max is 0\n int n = grid.size() + 1, m = grid.get(0).size() + 1;\n int[][] mat = new int[n][m], dp = new int[n][m];\n int x = 1, y = 1;\n for (List<Integer> row : grid) {\n for (int cell : row) {\n mat[x][y++] = cell;\n }\n x++;\n y = 1;\n }\n for (int i = 0; i < n; i++)\n mat[i][0] = Integer.MAX_VALUE;\n for (int j = 0; j < m; j++)\n mat[0][j] = Integer.MAX_VALUE;\n int min = Integer.MIN_VALUE, max = 0, max_i = 0, max_j = 0;\n for (int i = 1; i < n; i++)\n for (int j = 1; j < m; j++) {\n int valUp = dp[i - 1][j] + (mat[i][j] - mat[i - 1][j]);\n int valLeft = dp[i][j - 1] + (mat[i][j] - mat[i][j - 1]);\n dp[i][j] = Math.max(0, Math.max(valUp, valLeft));\n max = Math.max(max, dp[i][j]);\n if (valUp <= 0)\n min = Math.max(min, valUp);\n if (valLeft <= 0)\n min = Math.max(min, valLeft);\n // System.out.printf("up:%d, left:%d, dp:%d\\n", valUp, valLeft, dp[i][j]);\n }\n return max != 0 ? max : min;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
maximum-difference-score-in-a-grid | Java solution || Using 2D array to store max till that point from bottom end|| | java-solution-using-2d-array-to-store-ma-dn3x | 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 | user7683C | NORMAL | 2024-05-30T11:35:53.248702+00:00 | 2024-05-30T11:35:53.248719+00:00 | 4 | 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```\nclass Solution {\n public int maxScore(List<List<Integer>> grid) {\n int m=grid.size(),n=grid.get(0).size();\n int[][] dp=new int[m][n];\n dp[m-1][n-1]=grid.get(m-1).get(n-1);\n int ans=Integer.MIN_VALUE;\n for(int i=n-2;i>=0;i--){\n ans=Math.max(ans,dp[m-1][i+1]-grid.get(m-1).get(i));\n dp[m-1][i]=Math.max(grid.get(m-1).get(i),dp[m-1][i+1]);\n //ans=Math.max(ans,dp[m-1][i]-grid.get(m-1).get(i));\n \n }\n //System.out.println(ans);\n for(int i=m-2;i>=0;i--){\n ans=Math.max(ans,dp[i+1][n-1]-grid.get(i).get(n-1));\n dp[i][n-1]=Math.max(grid.get(i).get(n-1),dp[i+1][n-1]);\n //ans=Math.max(ans,dp[i][n-1]-grid.get(i).get(n-1));\n \n }\n //System.out.println(ans);\n for(int i=m-2;i>=0;i--){\n for(int j=n-2;j>=0;j--){\n ans=Math.max(ans,\n Math.max(\n dp[i+1][j]-grid.get(i).get(j),\n dp[i][j+1]-grid.get(i).get(j)\n )\n );\n dp[i][j]=Math.max(grid.get(i).get(j),Math.max(dp[i+1][j],dp[i][j+1]));\n //ans=Math.max(ans,dp[i][j]-grid.get(i).get(j));\n }\n }\n //System.out.println(ans);\n return ans;\n \n \n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
maximum-difference-score-in-a-grid | EASY DP RECURSIVE DP JAVA | easy-dp-recursive-dp-java-by-divyanshuag-vel0 | 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 | Divyanshuagarwal23 | NORMAL | 2024-05-22T13:20:43.035903+00:00 | 2024-05-22T13:20:43.035947+00:00 | 14 | 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```\nclass Solution {\n Integer[][] dp;\n public int maxScore(List<List<Integer>> grid) {\n int n = grid.size();\n int m = grid.get(0).size();\n int ans = -100000;\n dp = new Integer[n][m];\n for(int i = 0;i<grid.size();i++){\n for(int j = 0;j<grid.get(0).size();j++){\n if(i<n-1&&j<m-1){\n ans = Math.max(ans,Math.max(grid.get(i+1).get(j)-grid.get(i).get(j)+solve(i+1,j,grid,n,m),grid.get(i).get(j+1)-grid.get(i).get(j)+solve(i,j+1,grid,n,m)));\n }else if(i==n-1&&j<m-1){\n ans = Math.max(ans,grid.get(i).get(j+1)-grid.get(i).get(j)+solve(i,j+1,grid,n,m));\n }else if(j==m-1&&i<n-1){\n ans = Math.max(grid.get(i+1).get(j)-grid.get(i).get(j)+solve(i+1,j,grid,n,m),ans);\n }\n }\n }\n return ans;\n }\n public int solve(int row, int col, List<List<Integer>> grid, int n, int m){\n if(dp[row][col]!=null)\n return dp[row][col];\n int ans = 0;\n int a = 0;\n int b = 0;\n \n if(row+1<n){\n a = Math.max(a,grid.get(row+1).get(col)-grid.get(row).get(col)+solve(row+1,col,grid,n,m));\n }\n if(col+1<m){\n b = Math.max(b,grid.get(row).get(col+1)-grid.get(row).get(col)+solve(row,col+1,grid,n,m));\n }\n return dp[row][col] = Math.max(a,b);\n }\n}\n``` | 0 | 0 | ['Array', 'Dynamic Programming', 'Matrix', 'Java'] | 0 |
maximum-difference-score-in-a-grid | Intuitive DP solution | intuitive-dp-solution-by-tanshik-b639 | Intuition\nBy looking at the equation for finding the max difference, we can see that the result is equal to the max destination - origin.\n\nfor example, for t | tanshik | NORMAL | 2024-05-22T01:18:15.020379+00:00 | 2024-05-22T01:18:15.020411+00:00 | 20 | false | # Intuition\nBy looking at the equation for finding the max difference, we can see that the result is equal to the max destination - origin.\n\nfor example, for the path c1 -> c4, (c2 - c1) + (c3 - c2) + (c4 - c3) = c4 - c1. The intermediary steps cancel out.\n\nThen, the problem becomes finding the maximum difference from each origin. We know to optimize for this difference we have to subtract a cell value from the previously found minimum above or to the left of the current value.\n\nWe loop through every spot in the grid, \n\nFirst we find the current minimum, which is the minimum of the left cell and above cell. Then the maximum of the current cell and the current minimum and the curren result is set to the result. Then we update the dp array with the new minimum.\n\nComplexity is easy O(mn) for both, but we could save space by using the grid provided for tracking the minimum.\n\n# Code\n```\nclass Solution:\n def maxScore(self, grid: List[List[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n\n dp = [[10e5 for _ in range(n)] for _ in range(m)]\n\n # dp[i][j] = current minimum\n\n\n res = -10e5\n for i in range(m):\n for j in range(n):\n curr = min(dp[i - 1][j] if i > 0 else 10e5, dp[i][j - 1] if j > 0 else 10e5)\n res = max(res, grid[i][j] - curr)\n dp[i][j] = min(grid[i][j], curr)\n return res\n \n\n \n``` | 0 | 0 | ['Python3'] | 0 |
maximum-difference-score-in-a-grid | DP | dp-by-angle-e1s5 | 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 | angle_ | NORMAL | 2024-05-21T21:12:32.212905+00:00 | 2024-05-21T21:12:32.212925+00:00 | 3 | 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: o(m*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(m*n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def maxScore(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n """\n m,n = len(grid), len(grid[0])\n\n dp = [[-float(\'inf\')] * n for _ in range(m)]\n\n res = -float(\'inf\')\n\n for j in range(1, n):\n dp[0][j] = max(dp[0][j-1] + grid[0][j] - grid[0][j-1], grid[0][j] - grid[0][j-1])\n res = max(res, dp[0][j])\n \n for i in range(1, m):\n dp[i][0] = max(grid[i][0] - grid[i-1][0] + dp[i-1][0], grid[i][0] - grid[i-1][0])\n res = max(res, dp[i][0])\n\n for i in range(1, m):\n for j in range(1, n):\n dp[i][j] = max(dp[i-1][j] + grid[i][j]-grid[i-1][j], grid[i][j]-grid[i-1][j])\n dp[i][j] = max(dp[i][j], dp[i][j-1]+grid[i][j]-grid[i][j-1], grid[i][j]-grid[i][j-1])\n res = max(res, dp[i][j])\n return res if res != -float("inf") else -1\n\n``` | 0 | 0 | ['Python'] | 0 |
print-foobar-alternately | 5 Python threading solutions (Barrier, Event, Condition, Lock, Semaphore) with explanation | 5-python-threading-solutions-barrier-eve-jmla | Raise a barrier which makes both threads wait for each other before they are allowed to continue. foo prints before reaching the barrier. bar prints after reach | mereck | NORMAL | 2019-07-16T16:25:36.561824+00:00 | 2019-07-16T16:28:41.448921+00:00 | 12,052 | false | Raise a barrier which makes both threads wait for each other before they are allowed to continue. `foo` prints before reaching the barrier. `bar` prints after reaching the barrier. \n\n```\nfrom threading import Barrier\n\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.barrier = Barrier(2)\n\n def foo(self, printFoo):\n for i in range(self.n):\n printFoo()\n self.barrier.wait()\n\n def bar(self, printBar):\n for i in range(self.n):\n self.barrier.wait()\n printBar()\n```\n\nCount the number of times foo and bar was printed and only print foo if the number of times is equal. `bar` prints if foo was printed fewer times. Use Condition and `wait_for` to syncrhonize the threads.\n\n```\nfrom threading import Condition\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.foo_counter = 0\n self.bar_counter = 0\n self.condition = Condition()\n\n def foo(self, printFoo):\n for i in range(self.n):\n with self.condition:\n self.condition.wait_for(lambda: self.foo_counter == self.bar_counter)\n printFoo()\n self.foo_counter += 1\n self.condition.notify(1)\n\n def bar(self, printBar):\n for i in range(self.n):\n with self.condition:\n self.condition.wait_for(lambda: self.foo_counter > self.bar_counter)\n printBar()\n self.bar_counter += 1\n self.condition.notify(1)\n```\n\nEach thread can wait on each other to set their corresponding `foo_printed` and `bar_printed` events. Each thread also resets the corresponding printed events with `.clear()` for the next loop iteration.\n\n```\nfrom threading import Event\n\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.foo_printed = Event()\n self.bar_printed = Event()\n self.bar_printed.set()\n\n def foo(self, printFoo):\n for i in range(self.n):\n self.bar_printed.wait()\n self.bar_printed.clear()\n printFoo()\n self.foo_printed.set() \n\n def bar(self, printBar):\n for i in range(self.n):\n self.foo_printed.wait()\n self.foo_printed.clear()\n printBar()\n self.bar_printed.set() \n```\n\nUse two locks for the threads to signal to each other when the other should run. `bar_lock` starts in a locked state because we always want `foo` to print first.\n\n```\nfrom threading import Lock\n\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.foo_lock = Lock()\n self.bar_lock = Lock()\n self.bar_lock.acquire()\n\n def foo(self, printFoo):\n for i in range(self.n):\n self.foo_lock.acquire()\n printFoo()\n self.bar_lock.release()\n\n\tdef bar(self, printBar):\n for i in range(self.n):\n self.bar_lock.acquire()\n printBar()\n self.foo_lock.release()\n``` \n\nUse two Semaphores just as we used two locks. The `foo_gate` semaphore starts with a value of 1 because we want `foo` to print first.\n\n```\nfrom threading import Semaphore\n\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.foo_gate = Semaphore(1)\n self.bar_gate = Semaphore(0)\n\n def foo(self, printFoo):\n for i in range(self.n):\n self.foo_gate.acquire()\n printFoo()\n self.bar_gate.release()\n\n def bar(self, printBar):\n for i in range(self.n):\n self.bar_gate.acquire()\n printBar()\n self.foo_gate.release()\n```\n\n | 178 | 1 | [] | 15 |
print-foobar-alternately | [Java] Semaphore solution | java-semaphore-solution-by-yujd13-v85z | \nimport java.util.concurrent.Semaphore;\nclass FooBar {\n private int n;\n Semaphore s = new Semaphore(0);\n Semaphore s2 = new Semaphore(1);\n\n p | yujd13 | NORMAL | 2019-07-12T20:11:34.159056+00:00 | 2019-07-12T20:11:34.159098+00:00 | 11,550 | false | ```\nimport java.util.concurrent.Semaphore;\nclass FooBar {\n private int n;\n Semaphore s = new Semaphore(0);\n Semaphore s2 = new Semaphore(1);\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n\n for (int i = 0; i < n; i++) {\n\n // printFoo.run() outputs "foo". Do not change or remove this line.\n s2.acquire();\n\n printFoo.run();\n s.release();\n\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n\n for (int i = 0; i < n; i++) {\n\n // printBar.run() outputs "bar". Do not change or remove this line.\n s.acquire();\n\n printBar.run();\n s2.release();\n\n }\n }\n}\n``` | 66 | 3 | [] | 13 |
print-foobar-alternately | [Java] 4 Java threading solutions (Synchronized,Lock,Volatile,CAS) | java-4-java-threading-solutions-synchron-l5it | Overall,solution 2(lock+condition) performs better:\n comparing to solution 1,solution 2 using more waiting queues to avoid unnecessary notify, reduce lock comp | supertizzy | NORMAL | 2019-08-01T06:57:11.200241+00:00 | 2019-08-26T03:37:22.700001+00:00 | 7,175 | false | Overall,solution 2(lock+condition) performs better:\n* comparing to solution 1,solution 2 using more waiting queues to avoid unnecessary notify, reduce lock competition.\n* comparing to solution 3 and solution 4,solution 2 using synchronization queue to avoid unnecessary cpu execution.\n\n## 1.Synchronized(monitor exit happens-before monitor enter)\n\n```\n/**\n * @autor yeqiaozhu.\n * @date 2019-08-01\n */\npublic class FooBarSynchronized {\n\n\n private int n;\n //flag 0->foo to be print 1->foo has been printed\n private int flag = 0;\n\n\n public FooBarSynchronized(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n\n for (int i = 0; i < n; i++) {\n synchronized (this) {\n while (flag == 1) {\n this.wait();\n }\n // printFoo.run() outputs "foo". Do not change or remove this line.\n printFoo.run();\n flag = 1;\n this.notifyAll();\n }\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n\n for (int i = 0; i < n; i++) {\n synchronized (this) {\n while (flag == 0) {\n this.wait();\n }\n // printBar.run() outputs "bar". Do not change or remove this line.\n printBar.run();\n flag = 0;\n this.notifyAll();\n }\n }\n }\n}\n```\n\n## 2.Lock(volatile write happens-before volatile read)\n```\n\nimport java.util.concurrent.locks.Condition;\nimport java.util.concurrent.locks.ReentrantLock;\n\nclass FooBar {\n\n private int n;\n //flag 0->foo to be print 1->foo has been printed\n private int flag=0;\n ReentrantLock reentrantLock= new ReentrantLock();\n Condition fooPrintedCondition=reentrantLock.newCondition();\n Condition barPrintedCondition=reentrantLock.newCondition();\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n try {\n reentrantLock.lock();\n while (flag ==1){\n barPrintedCondition.await();\n }\n // printFoo.run() outputs "foo". Do not change or remove this line.\n printFoo.run();\n flag=1;\n fooPrintedCondition.signalAll();\n } catch (InterruptedException e) {\n e.printStackTrace();\n } finally {\n reentrantLock.unlock();\n }\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n reentrantLock.lock();\n while (flag==0){\n fooPrintedCondition.await();\n }\n // printBar.run() outputs "bar". Do not change or remove this line.\n \tprintBar.run();\n flag=0;\n \tbarPrintedCondition.signalAll();\n \treentrantLock.unlock();\n }\n }\n}\n```\n## 3.Voatile(volatile write happens-before volatile read)\n\n```\n\n/**\n * @autor yeqiaozhu.\n * @date 2019-08-01\n */\npublic class FooBarVolatile {\n\n private int n;\n //flag 0->foo to be print 1->foo has been printed using volatile\n private volatile int flag=0;\n\n\n public FooBarVolatile(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n\n for (int i = 0; i < n; i++) {\n while (true){\n if(flag==0){\n printFoo.run();\n flag=1;\n break;\n }\n Thread.sleep(1);\n }\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n\n for (int i = 0; i < n; i++) {\n while (true){\n if(flag==1){\n printBar.run();\n flag=0;\n break;\n }\n Thread.sleep(1);\n }\n }\n }\n}\n\n```\n\n## 4.CAS(volatile write happens-before volatile read)\n\n```\npackage P1115;\n\nimport java.util.concurrent.atomic.AtomicInteger;\n\n/**\n * @autor yeqiaozhu.\n * @date 2019-08-01\n */\npublic class FooBarCAS {\n\n\n private int n;\n ////flag 0->foo to be print 1->foo has been printed\n private AtomicInteger flag=new AtomicInteger(0);\n\n\n\n public FooBarCAS(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n\n for (int i = 0; i < n; i++) {\n while (!flag.compareAndSet(0,1)){\n Thread.sleep(1);\n }\n printFoo.run();\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n\n for (int i = 0; i < n; i++) {\n while (!flag.compareAndSet(1,0)){\n Thread.sleep(1);\n }\n printBar.run();\n }\n }\n\n}\n\n``` | 45 | 1 | [] | 16 |
print-foobar-alternately | C++ solution using mutex + CV (w/ explanation) | c-solution-using-mutex-cv-w-explanation-ld8ao | This is basically a semaphore. We use the flag fooTurn in the predicate of wait() to determine if the lock should be freed.\n\nBecause there are only two states | sdk__ | NORMAL | 2020-11-26T08:08:36.072014+00:00 | 2020-11-27T06:28:03.018659+00:00 | 4,031 | false | This is basically a semaphore. We use the flag `fooTurn` in the predicate of `wait()` to determine if the lock should be freed.\n\nBecause there are only two states (foo and bar), we can get away with using a boolean for the flag and `notify_one()`. If there were more states, we could scale this using an int flag and `notify_all()`.\n\nIf you\'re wondering why `foo` runs for the first time at all despite the `cv.wait()`, it\'s because the line is actually a shorthand for `while (!fooTurn) { cv.wait(lock); }`. Since `fooTurn` is initialized as true, the `cv.wait()` gets ignored.\n\n```\nclass FooBar {\nprivate:\n int n;\n std::mutex mtx;\n std::condition_variable cv;\n bool fooTurn = true; // is it foo\'s turn to run?\n\npublic:\n FooBar(int n) {\n this->n = n;\n }\n\n void foo(function<void()> printFoo) {\n for (int i = 0; i < n; i++) {\n std::unique_lock<std::mutex> lock(mtx);\n cv.wait(lock, [this] { return fooTurn; });\n\t\t\t\n \tprintFoo();\n\t\t\t\n fooTurn = false;\n cv.notify_one();\n }\n }\n\n void bar(function<void()> printBar) {\n for (int i = 0; i < n; i++) {\n std::unique_lock<std::mutex> lock(mtx);\n cv.wait(lock, [this] { return !fooTurn; });\n\t\t\t\n \tprintBar();\n\t\t\t\n fooTurn = true;\n cv.notify_one();\n }\n }\n};\n``` | 22 | 1 | ['C'] | 5 |
print-foobar-alternately | an easy c++ solution using two mutex | an-easy-c-solution-using-two-mutex-by-ti-brgu | \nclass FooBar {\nprivate:\n int n;\n mutex m1, m2;\n\npublic:\n FooBar(int n) {\n this->n = n;\n m2.lock();\n }\n\n void foo(funct | tinyalpha | NORMAL | 2019-07-22T12:52:23.990342+00:00 | 2019-07-22T12:52:23.990420+00:00 | 2,977 | false | ```\nclass FooBar {\nprivate:\n int n;\n mutex m1, m2;\n\npublic:\n FooBar(int n) {\n this->n = n;\n m2.lock();\n }\n\n void foo(function<void()> printFoo) {\n for (int i = 0; i < n; i++) {\n m1.lock();\n \t// printFoo() outputs "foo". Do not change or remove this line.\n \tprintFoo();\n m2.unlock();\n }\n }\n\n void bar(function<void()> printBar) {\n for (int i = 0; i < n; i++) {\n m2.lock();\n \t// printBar() outputs "bar". Do not change or remove this line.\n \tprintBar();\n m1.unlock();\n }\n }\n};\n``` | 19 | 11 | [] | 7 |
print-foobar-alternately | Java Semaphore with explaination | java-semaphore-with-explaination-by-flor-6zxz | The argument to the Semaphore instance is the number of "permits" that are available. It can be any integer, not just 0 or 1.\nFor runb all acquire() calls will | flora1155665 | NORMAL | 2019-07-14T04:02:36.525571+00:00 | 2019-07-14T04:03:13.704946+00:00 | 3,446 | false | The argument to the Semaphore instance is the number of "permits" that are available. It can be any integer, not just 0 or 1.\nFor `runb` all acquire() calls will block and tryAcquire() calls will return false, until you do a release().\nFor `runf` the first acquire() calls will succeed and the rest will block until the first one releases.\n\n\n```\nimport java.util.concurrent.*;\nclass FooBar {\n private int n;\n Semaphore runf, runb;\n \n public FooBar(int n) {\n this.n = n;\n runf = new Semaphore(1);\n runb = new Semaphore(0);\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n \trunf.acquire();\n printFoo.run();\n runb.release();\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n runb.acquire();\n \tprintBar.run();\n runf.release();\n }\n }\n}\n``` | 18 | 0 | ['Java'] | 3 |
print-foobar-alternately | C/C++ | 3 ways to solve: atomic; mutex; semaphore | cc-3-ways-to-solve-atomic-mutex-semaphor-sqhw | 1st way in C++: atomic\nExplanation: \n\natomic variables atomic<T> have mutex locks embedded in them. \n\nThe idea is that, if a thread acquires the lock, no o | nuoxoxo | NORMAL | 2022-08-07T09:52:53.025312+00:00 | 2022-08-07T09:52:53.025356+00:00 | 3,217 | false | # 1st way in C++: atomic\nExplanation: \n\natomic variables `atomic<T>` have `mutex locks` embedded in them. \n\nThe idea is that, if a thread acquires the lock, no other thread can acquire it (ie. modify it) until it is released.\n\nWell just how to tell the program to lock/unlock? \nUse `this_thread::yield()`, which, after a job (printFoo or printBar) is done, will `reschedule` the same job of that thread, allowing other threads to run.\n```go\nclass FooBar {\nprivate:\n int n;\n atomic<bool> alt; // added\n\npublic:\n FooBar(int n)\n {\n this->n = n;\n alt = false;\n }\n\n void foo(function<void()> printFoo) {\n \n for (int i = 0; i < n; i++)\n {\n\t\t/* solution part start */\n\t\twhile (alt)\n\t\t{\n\t\t\tthis_thread::yield();\n\t\t}\n\t\t/* end */\n\n\t\t// printFoo() outputs "foo". Do not change or remove this line.\n\t\tprintFoo();\n\n\t\talt = !alt; // added\n }\n }\n\n void bar(function<void()> printBar) {\n \n for (int i = 0; i < n; i++)\n {\n\t\t/* solution part start */\n\t\twhile (!alt)\n\t\t{\n\t\t\tthis_thread::yield();\n\t\t}\n\t\t/* end */\n\n\t\t// printBar() outputs "bar". Do not change or remove this line.\n\t\tprintBar();\n\n\t\talt = !alt; // added\n }\n }\n};\n```\n\n\n\n# 1st way in C: atomic\nExplanation: \n\nIn C, the same task is implemented using <kbd> signal </kbd>\n`sig_atomic_t alt` is equivalent to `atomic<bool> alt` in C++.\n\nOne perk to notice is that `sig_atomic_t` is actually of <kbd> int type </kbd>.\nIt means that even if we use an `int alt;`, the solution will also be accepted XD\n\nThen `sched_yield();` is equivalent to `this__thread::yied();` in C++.\n\n```go\n#include <signal.h>\n\ntypedef struct\n{\n int n;\n sig_atomic_t alt; // added\n} FooBar;\n\nFooBar* fooBarCreate(int n)\n{\n FooBar* obj = (FooBar*) malloc(sizeof(FooBar));\n obj->n = n;\n\n obj->alt = 0; // added\n\n return obj;\n}\n\nvoid foo(FooBar* obj)\n{ \n for (int i = 0; i < obj->n; i++)\n {\n /* added part start */\n while (obj->alt)\n {\n sched_yield();\n }\n /* end */\n\n // printFoo() outputs "foo". Do not change or remove this line.\n printFoo();\n\n obj->alt = 1; // added\n }\n}\n\nvoid bar(FooBar* obj)\n{ \n for (int i = 0; i < obj->n; i++)\n {\n /* added part start */\n while (!obj->alt)\n {\n sched_yield();\n }\n /* end */\n\n // printBar() outputs "bar". Do not change or remove this line.\n printBar();\n\n obj->alt = 0; // added\n }\n}\n\nvoid fooBarFree(FooBar* obj)\n{\n if (obj)\n free(obj);\n}\n```\n\n# 2nd way in C++: mutex\n\nThe most intuitive and simplest way is to use 2 `mutex`.\nOne for each function, ie. one mutex for `foo()` and the other for `bar()`.\n\nTo start, the "bar()" mutex is locked first. \nThen we alternatively lock and unlock both mutex:\n\n```go\nclass FooBar {\nprivate:\n int n;\n mutex food; // added\n mutex bart; // added\n\npublic:\n FooBar(int n)\n {\n this->n = n;\n bart.lock(); // added\n }\n\n void foo(function<void()> printFoo) {\n \n for (int i = 0; i < n; i++)\n {\n food.lock(); // added\n\n // printFoo() outputs "foo". Do not change or remove this line.\n \tprintFoo();\n\n bart.unlock(); // added\n }\n }\n\n void bar(function<void()> printBar) {\n \n for (int i = 0; i < n; i++)\n {\n bart.lock(); // added\n // printBar() outputs "bar". Do not change or remove this line.\n \tprintBar();\n\n food.unlock(); // added\n }\n }\n};\n```\n\n# 2nd way in C: mutex\n\nExplanation: \n\nSame things as in C++ mutex locking, just that some <kdb>writing</kbd> is different:\n\nTo declare mutex, use `pthread_mutex_t mtx`.\nWe also have to init them first `pthread_mutex_init(& mtx, NULL);`\nThen in each thread we do the same sequence, locking/unlocking each mutex:\n```cpp\npthread_mutex_lock(& mtx1);\nprint();\npthread_mutex_unlock(& mtx2)\n```\nThe entire code:\n```go\n# include "pthread.h"\n\ntypedef struct \n{\n pthread_mutex_t mtx_foo; // +\n pthread_mutex_t mtx_bar; // +\n int n;\n \n} FooBar;\n\nFooBar* fooBarCreate(int n)\n{\n FooBar* obj = (FooBar*) malloc(sizeof(FooBar));\n obj->n = n;\n\n pthread_mutex_init(& obj->mtx_foo, NULL); // +\n pthread_mutex_init(& obj->mtx_bar, NULL); // +\n\n return obj;\n}\n\nvoid foo(FooBar* obj)\n{\n for (int i = 0; i < obj->n; i++)\n {\n pthread_mutex_lock(& obj->mtx_bar); // +\n // printFoo() outputs "foo". Do not change or remove this line.\n printFoo();\n pthread_mutex_unlock(& obj->mtx_foo); // +\n }\n}\n\nvoid bar(FooBar* obj) {\n \n for (int i = 0; i < obj->n; i++)\n {\n pthread_mutex_lock(& obj->mtx_foo); // +\n // printBar() outputs "bar". Do not change or remove this line.\n printBar();\n pthread_mutex_unlock(& obj->mtx_bar); // +\n }\n}\n\nvoid fooBarFree(FooBar* obj)\n{\n if (obj)\n free(obj);\n}\n```\n\n# 3rd way in C++: semaphore\n\nIn this leetcode problem, using `semaphore` is similar to mutex in C. \n\n`sem_init` is equivalent to `pthread_mutex_init`\nThe second parameter is set to 0, as we have only one process (1 for management between processes; 0 for between threads of a single process). \n\nThe thrid parameter sets the initial value/order for a semaphore. In this case it is set to 0 and 1 respectively. \n\nThen we use `sem_wait` & `sem_wait` in place of mutex_lock and mutex_unlock.\n\n```go\n#include "semaphore.h" /* added */\n\nclass FooBar {\nprivate:\n int n;\n sem_t food;\n sem_t bart;\n\npublic:\n FooBar(int n)\n {\n this->n = n;\n sem_init(& food, 0, 0); /* added: */\n sem_init(& bart, 0, 1); /* added: */\n }\n\n void foo(function<void()> printFoo)\n {\n \n for (int i = 0; i < n; i++)\n {\n sem_wait(& bart); /* added */\n\n // printFoo() outputs "foo". Do not change or remove this line.\n\t\t\tprintFoo();\n\n sem_post(& food); /* added */\n }\n }\n\n void bar(function<void()> printBar)\n {\n \n for (int i = 0; i < n; i++)\n {\n sem_wait(& food); /* added */\n\n\t\t\t// printBar() outputs "bar". Do not change or remove this line.\n\t\t\tprintBar();\n\n sem_post(& bart); /* added */\n }\n }\n};\n```\n\n# 3rd way in C: semaphore\n```go\ntypedef struct \n{\n int n;\n\n sem_t foo_; // added\n sem_t bar_; // added\n \n} FooBar;\n\nFooBar* fooBarCreate(int n) {\n FooBar* obj = (FooBar*) malloc(sizeof(FooBar));\n obj->n = n;\n\n sem_init(& obj->foo_, 0, 0); // added\n sem_init(& obj->bar_, 0, 1); // added\n\n return obj;\n}\n\nvoid foo(FooBar* obj) {\n \n for (int i = 0; i < obj->n; i++)\n {\n sem_wait(& obj->bar_); // added\n\n // printFoo() outputs "foo". Do not change or remove this line.\n printFoo();\n\n sem_post(& obj->foo_); // added\n }\n}\n\nvoid bar(FooBar* obj) {\n \n for (int i = 0; i < obj->n; i++)\n {\n sem_wait(& obj->foo_); // added\n\n // printBar() outputs "bar". Do not change or remove this line.\n printBar();\n\n sem_post(& obj->bar_); // added\n }\n}\n\nvoid fooBarFree(FooBar* obj)\n{\n sem_destroy(& obj->foo_); // added\n sem_destroy(& obj->bar_); // added\n}\n``` | 17 | 0 | ['C', 'C++'] | 3 |
print-foobar-alternately | C++ Super-Simple Solution Using 2 Semaphores | c-super-simple-solution-using-2-semaphor-03ag | \n#include <semaphore.h>\n\nclass FooBar {\nprivate:\n int n;\n sem_t foo_sem;\n sem_t bar_sem;\n \npublic:\n FooBar(int n) {\n this->n = | yehudisk | NORMAL | 2020-11-19T17:38:06.272539+00:00 | 2020-11-19T17:40:33.640481+00:00 | 2,131 | false | ```\n#include <semaphore.h>\n\nclass FooBar {\nprivate:\n int n;\n sem_t foo_sem;\n sem_t bar_sem;\n \npublic:\n FooBar(int n) {\n this->n = n;\n sem_init(&foo_sem, 0, 1);\n sem_init(&bar_sem, 0, 0);\n }\n \n ~FooBar() {\n sem_destroy(&foo_sem);\n sem_destroy(&bar_sem);\n }\n\n void foo(function<void()> printFoo) {\n \n for (int i = 0; i < n; i++) {\n // lock foo semaphore\n sem_wait(&foo_sem); \n \t // printFoo() outputs "foo". Do not change or remove this line.\n \tprintFoo();\n // unlock bar semaphore\n sem_post(&bar_sem); \n }\n }\n\n void bar(function<void()> printBar) {\n \n for (int i = 0; i < n; i++) {\n // lock bar semaphore\n sem_wait(&bar_sem); \n \t // printBar() outputs "bar". Do not change or remove this line.\n \tprintBar();\n // unlock foo semaphore\n sem_post(&foo_sem); \n }\n }\n};\n```\n**Like it? please upvote...** | 15 | 0 | ['C'] | 6 |
print-foobar-alternately | python3: 40ms 86.64% Faster 100% Less memory, using threading.Lock | python3-40ms-8664-faster-100-less-memory-1osz | \nfrom threading import Lock\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.foo_lock = Lock()\n self.bar_lock = Lock()\n | sreejeet | NORMAL | 2020-04-29T18:13:02.948367+00:00 | 2020-04-29T18:13:02.948403+00:00 | 2,624 | false | ```\nfrom threading import Lock\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.foo_lock = Lock()\n self.bar_lock = Lock()\n self.bar_lock.acquire()\n\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.foo_lock.acquire()\n # printFoo() outputs "foo". Do not change or remove this line.\n printFoo()\n self.bar_lock.release()\n\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.bar_lock.acquire()\n # printBar() outputs "bar". Do not change or remove this line.\n printBar()\n self.foo_lock.release()\n``` | 14 | 0 | ['Python', 'Python3'] | 4 |
print-foobar-alternately | JAVA Boolean Volatile solution | java-boolean-volatile-solution-by-poorva-jfeq | \nclass FooBar {\n private int n;\n\n volatile boolean callFoo;\n volatile boolean callBar;\n\n public FooBar(int n) {\n | poorvank | NORMAL | 2019-07-13T12:13:55.029543+00:00 | 2019-07-13T12:13:55.029578+00:00 | 2,289 | false | ```\nclass FooBar {\n private int n;\n\n volatile boolean callFoo;\n volatile boolean callBar;\n\n public FooBar(int n) {\n this.n = n;\n callFoo = true;\n callBar = false;\n }\n\n public synchronized void foo(Runnable printFoo) throws InterruptedException {\n\n for (int i = 0; i < n; i++) {\n while (callBar) {\n wait();\n }\n // printFoo.run() outputs "foo". Do not change or remove this line.\n printFoo.run();\n callFoo = false;\n callBar = true;\n notifyAll();\n }\n }\n\n public synchronized void bar(Runnable printBar) throws InterruptedException {\n\n for (int i = 0; i < n; i++) {\n while (callFoo) {\n wait();\n }\n // printBar.run() outputs "bar". Do not change or remove this line.\n printBar.run();\n callBar = false;\n callFoo = true;\n notifyAll();\n }\n }\n }\n``` | 12 | 0 | [] | 5 |
print-foobar-alternately | C++, 104 ms, 10.5 MB | c-104-ms-105-mb-by-drus-pyl8 | Please, note : solution with mutex+condition_variable is 2-3x slower comparing with atomic.\n\n\nclass FooBar {\nprivate:\n int n;\n std::atomic<bool> b{t | drus | NORMAL | 2020-02-11T14:49:43.207774+00:00 | 2020-02-11T14:52:55.251883+00:00 | 1,703 | false | Please, note : solution with mutex+condition_variable is 2-3x slower comparing with atomic.\n\n```\nclass FooBar {\nprivate:\n int n;\n std::atomic<bool> b{true};\n\npublic:\n FooBar(int n) {\n this->n = n;\n }\n\n void foo(std::function<void()> printFoo)\n {\n for (int i = 0; i < n; i++)\n {\n while (!b.load(std::memory_order_acquire))\n {\n std::this_thread::yield();\n };\n printFoo();\n b.store(false, std::memory_order_release);\n }\n }\n\n void bar(std::function<void()> printBar)\n {\n for (int i = 0; i < n; i++)\n {\n while (b.load(std::memory_order_acquire))\n {\n std::this_thread::yield();\n };\n printBar();\n b.store(true, std::memory_order_release);\n }\n }\n};\n``` | 9 | 0 | [] | 3 |
print-foobar-alternately | Fast Java solution with good explanation. | fast-java-solution-with-good-explanation-eqpt | This is a standart "producer-consumer" problem. Read this article:\nhttps://www.baeldung.com/java-wait-notify\n\nI hope this helps :)\n\n\nclass FooBar {\n p | slav40 | NORMAL | 2019-07-19T07:07:34.167214+00:00 | 2019-07-19T07:13:34.253012+00:00 | 1,400 | false | This is a standart "producer-consumer" problem. Read this article:\nhttps://www.baeldung.com/java-wait-notify\n\nI hope this helps :)\n\n```\nclass FooBar {\n private int n;\n private boolean printfoo = true; // set value to true so we can assure that foo() will be called first\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n\n for (int i = 0; i < n; i++) {\n\n // printFoo.run() outputs "foo". Do not change or remove this line.\n synchronized (this) {\n /*\n If the first thread is here, that means it\'s already acquired\n this object\'s lock, so the second thread (or any other) gets blocked\n until the lock is released.\n */\n while (!printfoo) {\n /*\n If wait() is called, the first thread releases the lock (VERY IMPORTANT)\n and waits until the other thread calls notifyAll() inside the bar() method.\n That guarantees our code won\'t deadlock.\n */\n wait();\n }\n printFoo.run(); // print "foo"\n \n /*\n Here we set printFoo to false in order to assure that if the thread scheduler\n chooses this thread again, it will stop on the while loop and wait for the second\n one.\n */\n printfoo = false;\n\n /*\n When notifyAll() is called, the second thread will get out of the while loop\n inside bar() and continue its job (to print "bar")\n */\n notifyAll();\n }\n }\n }\n\n // the whole process is the same with the bar method\n public void bar(Runnable printBar) throws InterruptedException {\n\n for (int i = 0; i < n; i++) {\n\n // printBar.run() outputs "bar". Do not change or remove this line.\n synchronized (this) {\n while (printfoo) {\n wait();\n }\n printBar.run(); // print "bar"\n \n printfoo = true;\n notifyAll(); // wake up the first thread\n }\n\t\t\t// lock is released\n }\n }\n}\n``` | 9 | 0 | [] | 2 |
print-foobar-alternately | Can anyone help me understand why am I getting TLE? | can-anyone-help-me-understand-why-am-i-g-cig5 | This seems to be failing for n=4. When running the code in Intellij it seems to work fine:\n\n\nclass FooBar {\n private final int n;\n private volatile i | abc132 | NORMAL | 2019-07-16T22:17:50.680314+00:00 | 2019-07-16T22:17:50.680356+00:00 | 850 | false | This seems to be failing for n=4. When running the code in Intellij it seems to work fine:\n\n```\nclass FooBar {\n private final int n;\n private volatile int k = 0;\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException { \n for (int i = 0; i < n; i++) {\n while (k % 2 == 1);\n \tprintFoo.run();\n k++;\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException { \n for (int i = 0; i < n; i++) {\n while (k % 2 == 0);\n \tprintBar.run();\n k++;\n }\n }\n}\n```\n\nThis relies on spinlocks (which in this case I would expect would be OK). | 9 | 0 | [] | 4 |
print-foobar-alternately | Python 3 | 6 Approaches | Explanation | python-3-6-approaches-explanation-by-ido-tlv2 | Before you proceed\n- Intuition: Make sure the executing order using Lock or similar mechanism.\n- Technically 8 approaches since the first two can be rewrote u | idontknoooo | NORMAL | 2022-12-26T21:08:19.354262+00:00 | 2022-12-26T21:21:08.916317+00:00 | 1,243 | false | ## Before you proceed\n- **Intuition**: Make sure the executing order using `Lock` or similar mechanism.\n- Technically 8 approaches since the first two can be rewrote using `Semaphore`. \n\n## Approach \\#1. Lock/Semaphore only\n```python\nfrom threading import Lock\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.l1 = Lock() # Semaphore(1)\n self.l2 = Lock() # Semaphore(1)\n self.l2.acquire()\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.l1.acquire()\n printFoo()\n self.l2.release()\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.l2.acquire()\n printBar()\n self.l1.release()\n```\n\n## Approach \\#2. Lock/Semaphore + Barrier\n```python\nfrom threading import Barrier, Lock #, Semaphore\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.b = Barrier(2)\n self.l = Lock() # Semaphore(1)\n self.l.acquire()\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n printFoo()\n self.l.release()\n self.b.wait()\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n with self.l:\n printBar()\n self.b.wait()\n self.l.acquire()\n```\n## Approach \\#3. Condition only\n```python\nfrom threading import Condition\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.c1 = Condition()\n self.f = True\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n with self.c1:\n self.c1.wait_for(lambda: self.f)\n printFoo()\n self.f = False\n self.c1.notify(1)\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n with self.c1:\n self.c1.wait_for(lambda: not self.f)\n printBar()\n self.f = True\n self.c1.notify(1)\n```\n\n## Approach \\#4. Condition + Barrier\n```python\nfrom threading import Condition, Barrier\nclass FooBar: \n def __init__(self, n):\n self.n = n\n self.br = Barrier(2)\n self.c = Condition()\n self.f = False\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n with self.c:\n printFoo()\n self.f = True\n self.c.notify_all()\n self.br.wait()\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n with self.c:\n self.c.wait_for(lambda: self.f)\n printBar() \n self.f = False\n self.br.wait()\n```\n\n\n## Approach \\#5. Event only\n```python\nfrom threading import Event\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.e = Event()\n self.e1 = Event()\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n printFoo()\n self.e.set() \n self.e1.wait()\n self.e1.clear()\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.e.wait()\n printBar()\n self.e1.set()\n self.e.clear() \n```\n\n\n## Approach \\#6. Event + Barrier\n```python\nfrom threading import Event, Barrier\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.br = Barrier(2)\n self.e = Event()\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n printFoo()\n self.e.set()\n self.br.wait()\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.e.wait()\n printBar()\n self.e.clear()\n self.br.wait()\n``` | 8 | 0 | ['Concurrency', 'Python3'] | 2 |
print-foobar-alternately | C Solution using 2 semaphores | c-solution-using-2-semaphores-by-debbiea-r7p7 | \ntypedef struct \n{\n int n;\n sem_t foo_;\n sem_t bar_;\n \n}FooBar;\n\n\n\nFooBar* fooBarCreate(int n) \n{\n \n\n FooBar* obj = (FooBar*) m | debbiealter | NORMAL | 2020-08-11T10:23:00.889739+00:00 | 2020-08-11T10:26:56.583968+00:00 | 700 | false | ```\ntypedef struct \n{\n int n;\n sem_t foo_;\n sem_t bar_;\n \n}FooBar;\n\n\n\nFooBar* fooBarCreate(int n) \n{\n \n\n FooBar* obj = (FooBar*) malloc(sizeof(FooBar));\n obj->n = n;\n\t//initialize the semaphores\n sem_init(&obj->foo_, 0, 1);\n sem_init(&obj->bar_, 0, 0);\n return obj;\n}\n\n\n\nvoid foo(FooBar* obj) \n{\n \n for (int i = 0; i < obj->n; i++) \n {\n\t\t//lock\n sem_wait(&obj->foo_);\n \n // printFoo() outputs "foo". Do not change or remove this line.\n printFoo();\n \n\t\t//unlock\n sem_post(&obj->bar_); \n }\n}\n\nvoid bar(FooBar* obj) \n{\n \n for (int i = 0; i < obj->n; i++) \n {\n\t\t//lock\n sem_wait(&obj->bar_);\n\t\t\n // printBar() outputs "bar". Do not change or remove this line.\n printBar();\n\t\t\n\t\t//unlock\n sem_post(&obj->foo_);\n }\n}\n\nvoid fooBarFree(FooBar* obj) \n{\n\t//destroy the semaphores\n sem_destroy(&obj->foo_);\n sem_destroy(&obj->bar_);\n\t//free allocated memory\n free(obj);\n obj = NULL;\n}\n``` | 8 | 0 | [] | 0 |
print-foobar-alternately | [Java] Simple solution using two semaphores | java-simple-solution-using-two-semaphore-ha2e | The solution uses two semaphores which correspond to the foo and bar methods. \n- We initialize the foo semaphore with a single permit to permit the thread to i | michaeltruong | NORMAL | 2020-04-09T00:06:45.939875+00:00 | 2020-04-09T00:08:42.017860+00:00 | 847 | false | The solution uses two semaphores which correspond to the foo and bar methods. \n- We initialize the foo semaphore with a single permit to permit the thread to immediately acquire it and print foo. \n- The bar semaphore is initialized without a permit and requires something to increment the number of permits to be consumed. When we reach the bar method, it is blocked by ```bar.acquire()``` as there are no available permits. A permit is only available after we release it in the foo method\n- Logic is reflected in foo with the acquire/release logic\n```\nclass FooBar {\n\n private int n;\n private Semaphore foo;\n private Semaphore bar;\n\t\n public FooBar(int n) {\n this.n = n;\n this.foo = new Semaphore(1);\n this.bar = new Semaphore(0);\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n \n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n foo.acquire();\n \tprintFoo.run();\n bar.release();\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n \n // printBar.run() outputs "bar". Do not change or remove this line.\n bar.acquire();\n \tprintBar.run();\n foo.release();\n }\n }\n}\n``` | 8 | 0 | ['Java'] | 3 |
print-foobar-alternately | Simple solution with channels | Golang | simple-solution-with-channels-golang-by-klsjf | Approach\nAfter printing foo wait while bar is printed and the other way around. For this purpose we use a channel with zero capacity. Bar and Foo send a value | ivanterekh | NORMAL | 2024-02-29T14:53:10.988702+00:00 | 2024-02-29T14:53:10.988730+00:00 | 464 | false | # Approach\nAfter printing `foo` wait while `bar` is printed and the other way around. For this purpose we use a channel with zero capacity. `Bar` and `Foo` send a value to the channel, than wait for a feedback from each other.\n\n# Code\n```\ntype FooBar struct {\n\tn int\n ch chan int\n}\n\nfunc NewFooBar(n int) *FooBar {\n\treturn &FooBar{\n n: n,\n ch: make(chan int),\n }\n}\n\nfunc (fb *FooBar) Foo(printFoo func()) {\n\tfor i := 0; i < fb.n; i++ {\n // printFoo() outputs "foo". Do not change or remove this line.\n printFoo()\n fb.ch <- 0\n <-fb.ch\n\t}\n}\n\nfunc (fb *FooBar) Bar(printBar func()) {\n\tfor i := 0; i < fb.n; i++ {\n <-fb.ch\n // printBar() outputs "bar". Do not change or remove this line.\n printBar()\n fb.ch <- 0\n\t}\n}\n``` | 6 | 0 | ['Go'] | 0 |
print-foobar-alternately | [Java] Semaphore in Details Explanation With Brute Force Example | java-semaphore-in-details-explanation-wi-6rf7 | Brute Force Approach\n\n\nclass FooBar {\n private int n;\n int c = 0;\n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runn | hridoy100 | NORMAL | 2023-01-24T05:41:58.048256+00:00 | 2023-01-24T05:41:58.048301+00:00 | 2,101 | false | # Brute Force Approach\n\n```\nclass FooBar {\n private int n;\n int c = 0;\n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n while(c>0){\n continue;\n }\n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tprintFoo.run();\n c++;\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n while(c<1){\n continue;\n }\n // printBar.run() outputs "bar". Do not change or remove this line.\n \tprintBar.run();\n c--;\n }\n }\n}\n```\n\nThe while loop is just like acquiring lock. But this is exhaustive and will result into **TLE**. So, we have no choice but to use `Semaphores`.\n\n\n# Solution Using Semaphore\n\n```\nclass FooBar {\n private int n;\n Semaphore foo_lock, bar_lock;\n public FooBar(int n) {\n this.n = n;\n foo_lock = new Semaphore(1); // foo can pass\n bar_lock = new Semaphore(0); // bar cannot\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n foo_lock.acquire(); // foo_lock is 1, so acquire lock\n // acquired lock. foo_lock = 0 now..\n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tprintFoo.run();\n bar_lock.release(); // released lock. bar_lock = 1 now..\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n bar_lock.acquire(); // bar_lock is 1, so acquire lock\n // bar_lock = 0 now..\n // printBar.run() outputs "bar". Do not change or remove this line.\n \tprintBar.run();\n foo_lock.release(); // released lock. foo_lock = 1 now..\n }\n }\n}\n```\n\nYou probably know the basics of **Semaphores**. To acquire locks semaphore values need to be > 0. When the value is <= 0 we cannot acquire lock of that `Semaphore`. | 6 | 0 | ['Java'] | 2 |
print-foobar-alternately | Java | Beat 85% | Simple wait and notify solution | java-beat-85-simple-wait-and-notify-solu-0uxr | Simple Wait and Notify logic. Please upvote \n\n~~~\nclass FooBar {\n private int n;\n\n public FooBar(int n) {\n this.n = n;\n }\n \n vol | rougef4ak | NORMAL | 2022-09-05T16:51:10.036198+00:00 | 2022-09-05T16:52:00.842089+00:00 | 1,736 | false | Simple Wait and Notify logic. Please upvote \n\n~~~\nclass FooBar {\n private int n;\n\n public FooBar(int n) {\n this.n = n;\n }\n \n volatile boolean printF = true;\n\n public void foo(Runnable printFoo) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n synchronized (this){\n if(!printF){\n this.wait();\n }\n printFoo.run();\n printF = false;\n this.notifyAll();\n }\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n synchronized (this){\n if(printF){\n this.wait();\n }\n printBar.run();\n printF = true;\n this.notifyAll();\n }\n }\n }\n}\n~~~ | 6 | 0 | ['Java'] | 2 |
print-foobar-alternately | c++ efficient & clean solution using 2 semaphore | c-efficient-clean-solution-using-2-semap-uawi | // we have to include the semaphore header file ,as c++ 20 is not available in our LC editor currently\n\n\n#include <semaphore.h>\nclass FooBar {\nprivate:\n | NextThread | NORMAL | 2022-01-17T13:49:59.600331+00:00 | 2022-01-17T13:49:59.600375+00:00 | 406 | false | // we have to include the semaphore header file ,as c++ 20 is not available in our LC editor currently\n\n```\n#include <semaphore.h>\nclass FooBar {\nprivate:\n int n;\n sem_t foo_sem;\n sem_t bar_sem;\n \npublic:\n FooBar(int n) {\n this->n = n;\n sem_init(&foo_sem, 0, 1);\n sem_init(&bar_sem, 0, 0);\n }\n \n ~FooBar() {\n sem_destroy(&foo_sem);\n sem_destroy(&bar_sem);\n }\n\n void foo(function<void()> printFoo) {\n \n for (int i = 0; i < n; i++) {\n // lock foo semaphore\n sem_wait(&foo_sem); \n \t // printFoo() outputs "foo". Do not change or remove this line.\n \tprintFoo();\n // unlock bar semaphore\n sem_post(&bar_sem); \n }\n }\n\n void bar(function<void()> printBar) {\n \n for (int i = 0; i < n; i++) {\n // lock bar semaphore\n sem_wait(&bar_sem); \n \t // printBar() outputs "bar". Do not change or remove this line.\n \tprintBar();\n // unlock foo semaphore\n sem_post(&foo_sem); \n }\n }\n};\n``` | 5 | 0 | ['C'] | 1 |
print-foobar-alternately | [JAVA] Very Simple Synchronized Solution | java-very-simple-synchronized-solution-b-ni1k | \nclass FooBar {\n private int n;\n boolean runFoo; // boolean to check if Thread A (the one calling foo()) is in execution\n \n public FooBar(int n | aarjavsheth | NORMAL | 2021-03-20T06:27:08.264545+00:00 | 2021-03-20T06:27:08.264572+00:00 | 1,083 | false | ``` \nclass FooBar {\n private int n;\n boolean runFoo; // boolean to check if Thread A (the one calling foo()) is in execution\n \n public FooBar(int n) {\n this.n = n;\n runFoo = true;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n \n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tsynchronized(this) {\n // wait until bar() is running\n\t\t\t\twhile(!runFoo) {\n wait();\n }\n printFoo.run();\n runFoo = false;\n notifyAll();\n }\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n \n // printBar.run() outputs "bar". Do not change or remove this line.\n synchronized(this) {\n\t\t\t\t// wait until foo() is running\n while(runFoo) {\n wait();\n }\n printBar.run();\n runFoo = true;\n notifyAll();\n }\n }\n }\n}\n``` | 5 | 0 | ['Java'] | 1 |
print-foobar-alternately | C++ std::atomic<bool> solution with yielding | c-stdatomicbool-solution-with-yielding-b-ga3g | This solution uses no mutexes/locks, and it is somewhat faster than locking/conditionals on LeetCode\'s OJ. That being said, if you take this code and run it on | aboulmagd | NORMAL | 2019-12-05T00:23:46.439919+00:00 | 2019-12-05T00:24:35.783199+00:00 | 568 | false | This solution uses no mutexes/locks, and it is somewhat faster than locking/conditionals on LeetCode\'s OJ. That being said, if you take this code and run it on your own machine, it may be a LOT slower than the one that uses locks/conditionals and has to wait/notify...So take this solution with a grain of salt, please...\n\n```\nclass FooBar\n{\nprivate:\n int n;\n std::atomic<bool> toPrintFoo;\n \npublic:\n FooBar(int n)\n {\n this->n = n;\n this->toPrintFoo.store(true, std::memory_order_seq_cst);\n }\n\n void foo(function<void()> printFoo)\n {\n for (int i = 0; i < n;)\n {\n if (toPrintFoo.load(std::memory_order_seq_cst))\n {\n // printFoo() outputs "foo". Do not change or remove this line.\n \t printFoo();\n \n toPrintFoo.store(false, std::memory_order_seq_cst);\n \n i++;\n }\n else\n {\n // yield this thread (on a single core, letting the other thread take over)\n // to the OS to determine whether higher or equal priority processes/threads\n // can jump on the core...\n std::this_thread::yield();\n }\n }\n }\n\n void bar(function<void()> printBar)\n {\n for (int i = 0; i < n;)\n {\n if (!toPrintFoo.load(std::memory_order_seq_cst))\n {\n // printFoo() outputs "foo". Do not change or remove this line.\n \t printBar();\n \n toPrintFoo.store(true, std::memory_order_seq_cst);\n \n i++;\n }\n else\n {\n // yield this thread (on a single core, letting the other thread take over)\n // to the OS to determine whether higher or equal priority processes/threads\n // can jump on the core...\n std::this_thread::yield();\n }\n }\n }\n};\n``` | 5 | 0 | ['C'] | 2 |
print-foobar-alternately | Python solution using Lock | python-solution-using-lock-by-nightybear-5etu | Hi, below is my python solution using Lock, feel free to give idea.\n\n\nfrom threading import Lock\nclass FooBar:\n def __init__(self, n):\n self.n = | nightybear | NORMAL | 2019-08-16T03:46:37.095209+00:00 | 2019-08-16T03:46:37.095247+00:00 | 1,017 | false | Hi, below is my python solution using Lock, feel free to give idea.\n\n```\nfrom threading import Lock\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.lock1 = Lock()\n self.lock2 = Lock()\n \n self.lock1.acquire()\n\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n \n for i in range(self.n):\n self.lock2.acquire()\n # printFoo() outputs "foo". Do not change or remove this line.\n printFoo()\n self.lock1.release()\n\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n \n for i in range(self.n):\n self.lock1.acquire()\n # printBar() outputs "bar". Do not change or remove this line.\n printBar()\n self.lock2.release()\n\n``` | 5 | 1 | ['Python', 'Python3'] | 1 |
print-foobar-alternately | C# using AutoResetEvent | c-using-autoresetevent-by-alphasierra-y7ts | ```class FooBar\n {\n\t\t// initialized to true to indicate the first time there is no need to wait i.e. "foo" gets printed rightaway\n private AutoRe | alphasierra | NORMAL | 2019-07-13T17:56:37.438784+00:00 | 2019-07-13T17:57:02.356676+00:00 | 328 | false | ```class FooBar\n {\n\t\t// initialized to true to indicate the first time there is no need to wait i.e. "foo" gets printed rightaway\n private AutoResetEvent evt1 = new AutoResetEvent(true);\n\t\t\n\t\t// initialize to false to indicate that first time there is a need to wait i.e. "bar" won\'t get printed until told.\n private AutoResetEvent evt2 = new AutoResetEvent(false);\n\n private int n;\n\n public FooBar(int n)\n {\n this.n = n;\n }\n\n public void Foo()\n {\n for (int i = 0; i < n; i++)\n {\n evt1.WaitOne();\n\n Console.Write("foo");\n\n\t\t\t\t// Signal to the other guy that they are ok to proceed.\n evt2.Set();\n }\n }\n\n public void Bar()\n {\n\n for (int i = 0; i < n; i++)\n {\n evt2.WaitOne();\n\n Console.Write("bar");\n\n\t\t\t\t// Signal to the other guy that they are ok to proceed.\n evt1.Set();\n }\n }\n } | 5 | 0 | [] | 0 |
print-foobar-alternately | Python 3 - Semaphore | python-3-semaphore-by-awice-o5wz | \nfrom threading import Semaphore\n\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.foosema = Semaphore(1)\n self.barsema = | awice | NORMAL | 2019-07-12T21:04:41.329113+00:00 | 2019-07-12T21:04:52.359779+00:00 | 1,168 | false | ```\nfrom threading import Semaphore\n\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.foosema = Semaphore(1)\n self.barsema = Semaphore(0)\n\n def foo(self, printFoo):\n for i in range(self.n):\n self.foosema.acquire()\n printFoo()\n self.barsema.release()\n\n def bar(self, printBar):\n for i in range(self.n):\n self.barsema.acquire()\n printBar()\n self.foosema.release()\n``` | 5 | 1 | [] | 1 |
print-foobar-alternately | Simple Solution using await & notify | java | simple-solution-using-await-notify-java-iajke | Intuition\nHere i am using boolean flag and concept of bussy wait to check on condition and print something.\n\ni wait till the condition is not in desired stat | gaurav-x5 | NORMAL | 2023-08-27T20:14:17.198418+00:00 | 2023-08-27T20:21:49.877861+00:00 | 1,137 | false | # Intuition\nHere i am using boolean flag and concept of bussy wait to check on condition and print something.\n\ni wait till the condition is not in desired state and once someOther thread notifies me the values has changed i check the condition again and proceed if the condition succeeds.\n\n# Code\n```\nclass FooBar {\n private int n;\n boolean printed;\n\n public FooBar(int n) {\n this.n = n;\n printed = false;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n \n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tsynchronized (this) {\n while (printed == true) {\n wait();\n }\n\n printFoo.run();\n printed = true;\n notify();\n } \n\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n \n // printBar.run() outputs "bar". Do not change or remove this line.\n \tsynchronized (this) {\n while (printed == false) { \n wait();\n }\n printBar.run();\n printed = false;\n notify();\n }\n }\n }\n}\n```\n\nBelow is another approach using reetrantLock\n\n# ReetrantLock Approach\nNote: similar to above approach\nwe need condition construct offered by lock to signal and wait onto\nwait ~ condition.await()\nnotify ~ condition.signal()\n# Code\n```\nclass FooBar {\n private int n;\n boolean printed;\n Lock lock = new ReentrantLock();\n Condition condition = lock.newCondition();\n\n public FooBar(int n) {\n this.n = n;\n printed = false;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n \n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tlock.lock();\n while (printed == true) {\n condition.await();\n }\n\n printFoo.run();\n printed = true;\n condition.signal();\n lock.unlock(); \n\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n \n // printBar.run() outputs "bar". Do not change or remove this line.\n \tlock.lock();\n while (printed == false) { \n condition.await();\n }\n printBar.run();\n printed = false;\n condition.signal();\n lock.unlock();\n }\n }\n}\n```\n | 4 | 0 | ['Java'] | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.