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
number-of-submatrices-that-sum-to-target
Easy C++ Soln || Analogous to number of subarray sum k || Explanied
easy-c-soln-analogous-to-number-of-subar-gjde
\nclass Solution {\npublic:\n //just like number of subarray with sum k only dimension is 2\n int numSubmatrixSumTarget(vector<vector<int>>& mat, int targ
mitedyna
NORMAL
2021-06-02T16:57:43.705078+00:00
2021-06-02T16:57:43.705124+00:00
285
false
```\nclass Solution {\npublic:\n //just like number of subarray with sum k only dimension is 2\n int numSubmatrixSumTarget(vector<vector<int>>& mat, int target) {\n vector<vector<int>> pre=mat;\n // row wise sum\n for(int r=1;r<mat.size();r++){\n for(int i=0;i<mat[0].size();i++){\n pre[r][i]+=pre[r-1][i];\n }\n }\n unordered_map<int,int> mp;\n int ans=0;\n for(int r=0;r<mat.size();r++){\n for(int i=r;i<mat.size();i++){\n int sum=0;\n mp.clear();\n mp[sum]++;\n for(int j=0;j<mat[0].size();j++){\n sum+=pre[i][j]-(r>0?pre[r-1][j]:0);\n if(mp.count(sum-target))ans+=mp[sum-target];\n mp[sum]++;\n }\n }\n }\n return ans;\n \n }\n};\n```
3
4
['C']
0
number-of-submatrices-that-sum-to-target
[C++] DP brute force and 2-sum flavored, a legend a 1-D guy manage 2-D dream
c-dp-brute-force-and-2-sum-flavored-a-le-h3cj
Approach 1: DP [1]\nTime/Space: O(M*N^2); O(1); where M, N is the row and column size of the given matrix\nmotivation:\nIt is about a legend a 1-D guy manage 2-
codedayday
NORMAL
2021-04-17T15:56:59.075731+00:00
2021-04-18T18:56:00.387260+00:00
188
false
Approach 1: DP [1]\nTime/Space: O(M*N^2); O(1); where M, N is the row and column size of the given matrix\nmotivation:\nIt is about a legend a 1-D guy manage 2-D dream\n```\nclass Solution {\npublic:\n int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {\n const int m = matrix.size(), n = matrix[0].size();\n for(int i = 0; i < m; i++)\n for(int j = 1; j < n; j++)\n matrix[i][j] += matrix[i][j-1];\n \n int ans = 0;\n for(int l = 0; l < n; l++) // l: left column index\n for(int r = l; r < n; r++){ //r: right column index\n unordered_map<int, int> counts{{0, 1}};\n int cur = 0; //this guy working hard, coming from 1-D world, but can watch 2-D by collecting runnign rums of different rows between col l & r\n for(int i = 0; i < m; i++){\n cur += matrix[i][r] - (l > 0 ? matrix[i][l - 1] : 0); \n ans += counts[cur - target];\n ++counts[cur];\n } \n }\n return ans; \n }\n};\n```\n\n\nApproach 2: DP brute force (WARNING: will cause TLE error)\nTime/Space: O(N^4); O(N)\n```\nclass Solution {\npublic:\n int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {\n const int m = matrix.size(), n = matrix[0].size();\n vector<vector<int>> sums(m + 1, vector<int>(n + 1, 0));\n for(int i = 1; i <= m; i++)\n for(int j = 1; j <= n; j++)\n sums[i][j] = sums[i - 1][j] + sums[i][j - 1] - sums[i - 1][j - 1] + matrix[i-1][j-1];\n \n int ans = 0;\n for(int i = 1; i <= m; i++)\n for(int j = 1; j <= n; j++)\n for(int r = 1; r <= i; r++)\n for(int c = 1; c <= j; c++)\n if(target == sums[i][j] - sums[i][c - 1] - sums[r - 1][j] + sums[r - 1][c - 1]) ans++;\n return ans;\n }\n};\n```\n\n[1] https://www.cnblogs.com/grandyang/p/14588186.html
3
0
[]
1
number-of-submatrices-that-sum-to-target
Java clean solution O(R2 * C) compexity
java-clean-solution-or2-c-compexity-by-s-sui4
\nclass Solution {\n public int numSubmatrixSumTarget(int[][] matrix, int target) {\n HashMap<Integer, Integer> count = new HashMap();\n int []
shubhamdarad
NORMAL
2021-04-17T08:31:13.957417+00:00
2021-04-17T08:31:13.957456+00:00
362
false
```\nclass Solution {\n public int numSubmatrixSumTarget(int[][] matrix, int target) {\n HashMap<Integer, Integer> count = new HashMap();\n int [] dp = new int [matrix[0].length];\n int res = 0;\n for(int i = 0;i <matrix.length;i++){\n for(int j =i; j < matrix.length;j++){\n count.put(0, 1);\n res += numSubmatrixSumTarget(i, j, matrix, target, count, dp);\n count.clear();\n }\n }\n return res;\n }\n \n private int numSubmatrixSumTarget(int first, int second, int [][] matrix, int target, HashMap<Integer, Integer> count, int [] dp){\n int res = 0;\n int sum = 0;\n for(int i = 0;i<matrix[first].length;i++){\n sum += matrix[second][i];\n dp[i] = sum+ (first == second?0:dp[i]);\n res += count.getOrDefault(dp[i] - target, 0);\n count.put(dp[i], count.getOrDefault(dp[i], 0)+1);\n }\n return res;\n }\n}\n```
3
1
[]
0
number-of-submatrices-that-sum-to-target
C++ Solution
c-solution-by-saurabhvikastekam-2jht
class Solution {\npublic:\n int numSubmatrixSumTarget(vector>& A, int t) \n {\n \n int i,n,m;\n n=A.size();\n if(n==0)\n
SaurabhVikasTekam
NORMAL
2021-04-17T07:26:38.718989+00:00
2021-04-17T07:26:38.719021+00:00
326
false
class Solution {\npublic:\n int numSubmatrixSumTarget(vector<vector<int>>& A, int t) \n {\n \n int i,n,m;\n n=A.size();\n if(n==0)\n {\n return 0;\n }\n m=A[0].size();\n if(m==0)\n {\n return 0;\n }\n \n int j;\n for(i=0;i<n;i++)\n {\n for(j=1;j<m;j++)\n {\n A[i][j]+=A[i][j-1];\n }\n }\n \n int ans=0;\n map<int,int>ma;\n \n for(int sc=0;sc<m;sc++)\n {\n for(int cc=sc;cc<m;cc++)\n {\n ma.clear();\n ma[0]=1;\n int sum=0;\n for(i=0;i<n;i++)\n {\n sum+=A[i][cc]-(sc>0?A[i][sc-1]:0);\n ans+=ma[sum-t]; \n ma[sum]++;\n }\n }\n }\n \n return ans;\n \n }\n};
3
2
['C', 'C++']
0
number-of-submatrices-that-sum-to-target
Simple Java Solution, No hash map
simple-java-solution-no-hash-map-by-sash-ybnj
\nclass Solution {\n public int numSubmatrixSumTarget(int[][] matrix, int target) {\n int ans = 0;\n\n for(int i = 0; i<matrix[0].length;i++){/
sashawanchen
NORMAL
2021-02-02T09:30:36.402077+00:00
2021-02-02T09:30:36.402131+00:00
601
false
```\nclass Solution {\n public int numSubmatrixSumTarget(int[][] matrix, int target) {\n int ans = 0;\n\n for(int i = 0; i<matrix[0].length;i++){//left col\n int[] sum = new int[matrix.length];\n for(int m = i; m<matrix[0].length;m++){//right col\n for(int j = 0; j<matrix.length;j++){\n sum[j]+=matrix[j][m];//add left to right\n if(sum[j]==target)ans++; \n }\n for(int j = 0; j<matrix.length;j++){//up row\n int summe=0; \n for(int n = j; n<matrix.length;n++){//down row\n summe+=sum[n];add up to down\n if(n!=j&&summe==target)ans++;\n }\n }\n }\n }\n \n return ans;\n\n }\n}\n```
3
0
['Java']
0
number-of-submatrices-that-sum-to-target
Dynamic programming approach with video explanation
dynamic-programming-approach-with-video-ytw14
https://www.youtube.com/watch?v=i5UoDZbQ94Q
thetechgranth
NORMAL
2020-11-19T15:01:24.433726+00:00
2020-11-19T15:01:24.433769+00:00
393
false
https://www.youtube.com/watch?v=i5UoDZbQ94Q
3
0
[]
1
number-of-submatrices-that-sum-to-target
Java prefix sum + hashmap
java-prefix-sum-hashmap-by-hobiter-d50i
\n public int numSubmatrixSumTarget(int[][] mx, int t) {\n int res = 0, m = mx.length, n = mx[0].length;\n for (int i = 0;i < m; i++) {\n
hobiter
NORMAL
2020-07-03T19:46:19.628338+00:00
2020-07-03T19:46:19.628384+00:00
293
false
```\n public int numSubmatrixSumTarget(int[][] mx, int t) {\n int res = 0, m = mx.length, n = mx[0].length;\n for (int i = 0;i < m; i++) {\n for (int j = 1; j < n; j++) {\n mx[i][j] += mx[i][j - 1];\n }\n }\n for (int l = 0; l < n; l++) {\n for (int r = l; r < n; r++) {\n Map<Integer, Integer> map = new HashMap<>(); \n map.put(0, 1);// init empty sub mx;\n for (int i = 0, sum = 0; i < m; i++) {\n sum += (mx[i][r] - (l == 0 ? 0 : mx[i][l - 1]));\n res += map.getOrDefault(sum - t, 0);\n map.put(sum, map.getOrDefault(sum, 0) + 1);\n }\n }\n }\n return res;\n }\n```
3
1
[]
0
number-of-submatrices-that-sum-to-target
C++ || Well-Commented || O(N*N*M) || std::unordered_map || Explanation MaximumSumSubmatrix
c-well-commented-onnm-stdunordered_map-e-oh8c
In a nutshell the approach is to choose all pairs of rows and shrink the bundle (chosen rows alongwith rows in between them) into an array (summing up entries
pyder
NORMAL
2020-06-13T10:55:21.692577+00:00
2020-06-13T10:58:09.795263+00:00
336
false
In a nutshell the approach is to choose all pairs of rows and shrink the bundle (chosen rows alongwith rows in between them) into an array (summing up entries in each column together) and now **finding the number of subarrays in this array whose sum is equal to the target in O(M).**\n\nThe overall complexity becomes O(N * N * M).\n\n\n```\nclass Solution {\npublic:\n \n //Another classical problem of finding number of subarrays having sum equal to target in the array\n int numSubarraySumTarget(vector<int> &arr,int target){\n int num_of_subarray=0;\n unordered_map<int,int> mp;\n mp.insert({0,1});\n int curr_sum=0;\n for(int i=0;i<arr.size();i++){\n curr_sum+=arr[i];\n if(mp.find(curr_sum-target)!=mp.end()) num_of_subarray+=mp[curr_sum-target];\n mp[curr_sum]++;\n }\n return num_of_subarray;\n }\n \n \n int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {\n \n int n=matrix.size(); //number of rows in the matrix\n if(n==0) return 0; //If there are no rows in a matrix then there is no submatrix for any target \n int m=matrix[0].size(); //number of columns in the matrix\n \n int number_of_submatrices=0;\n \n \n //choosing two rows adding there elements of same columns and creating the array out of it / Simply shrinking the bundle of rows to a 1-D array\n for(int row_x1=0;row_x1<n;row_x1++){\n vector<int> sum_array(m,0);\n for(int row_x2=row_x1;row_x2<n;row_x2++){\n \n for(int i=0;i<m;i++) sum_array[i]+=matrix[row_x2][i];\n \n //Find the number of subarrays that equal to the target in this shrinked array. \n number_of_submatrices+=numSubarraySumTarget(sum_array,target);\n \n }\n \n }\n \n return number_of_submatrices;\n }\n};\n```\n\n***There is another variation of the same problem where we find the submatrix with the maximum sum.This can be done by following the first part of choosing rows and bundelling up similarly and then applying the kaden\'s algorithm of the array in O(M).***
3
0
[]
1
number-of-submatrices-that-sum-to-target
Easy to understand solution
easy-to-understand-solution-by-sonaligar-mhz5
It is actually a combination of 2 problems but slightly twisted:\nproblem 1: Find number of sub arrays with target sum\nproblem 2: Find largest sub matrix with
sonaligarg19
NORMAL
2020-03-18T00:56:41.625913+00:00
2020-03-18T00:56:41.625964+00:00
494
false
It is actually a combination of 2 problems but slightly twisted:\nproblem 1: Find number of sub arrays with target sum\nproblem 2: Find largest sub matrix with target sum\n\nFor problem 1: I followed the same hashmap approach as listed in this leetcode problem: https://leetcode.com/problems/subarray-sum-equals-k/solution/\nFor problem 2: here is an excellent video which you will understand in 1 go. https://www.youtube.com/watch?time_continue=173&v=yCQN096CwWM&feature=emb_logo\n\nNow just twist problem 2 and instead of saying find Maximum Sum Rectangular Submatrix, find all subarrays with sum equal to k.\n\nIf you understand problem 2 deeply then you will understand that the problem is actually very simple and not complex at all.\n\n***Java***\n```\n public int numSubmatrixSumTarget(int[][] matrix, int target) {\n if(matrix == null) {\n return 0;\n }\n int rowLen = matrix.length;\n int colLen = matrix[0].length;\n int answer = 0;\n\n for(int left = 0;left < colLen;left++) {\n int[] tempArr = new int[rowLen];\n for(int right = left; right < colLen; right++) {\n for(int row = 0; row < rowLen; row++) {\n tempArr[row] = tempArr[row] + matrix[row][right];\n }\n answer = answer + subarraySum(tempArr, target);\n }\n }\n return answer;\n }\n\n public int subarraySum(int[] arr, int target) {\n Map<Integer, Integer> map = new HashMap<>();\n map.put(0, 1);\n int ans = 0;\n int sumSoFar = 0;\n for(int i=0;i<arr.length ;i++) {\n sumSoFar = sumSoFar + arr[i];\n int requiredSum = sumSoFar - target;\n if(map.containsKey(requiredSum)) {\n ans = ans + map.get(requiredSum);\n }\n map.put(sumSoFar, map.get(sumSoFar) != null ? map.get(sumSoFar) + 1 : 1);\n }\n return ans;\n }\n\t
3
0
[]
1
number-of-submatrices-that-sum-to-target
From O(N^4) to O(N^3)
from-on4-to-on3-by-quadpixels-nxqi
O(N^4):\n Enumerate all (r0, r1, c0, c1) pairs. Each variable is 1 layer in a nested loop. With 4 levels of loop, complexity gets to O(N^4).\n\nO(N^3):\n Enumer
quadpixels
NORMAL
2019-06-02T04:10:21.768835+00:00
2019-06-02T04:12:06.571924+00:00
1,198
false
O(N^4):\n* Enumerate all (r0, r1, c0, c1) pairs. Each variable is 1 layer in a nested loop. With 4 levels of loop, complexity gets to O(N^4).\n\nO(N^3):\n* Enumerate all (c0, c1) pairs. This gives O(N^2) complexity.\n* Then, for a pair, we get a sub-slice of the matrix. We compute the prefix-sum that says (what\'s the sum of the first `r` rows in the slice?) and convert this into "find a subsequence that sums to a certain target" problem. This can be solved in O(N) by storing all prefix sums into a hash table.\n* In total, the O(N) loop is nested in the O(N^2) loop, giving O(N^3) overall.\n\nIn the following code, setting variable `SLOW` to true gives O(N^4). Setting it to false gives O(N^3).\n\n(However I was not debugging fast enough so I could not submit the solution before the end of the context X_X )\n\n```\nclass Solution {\npublic:\n int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {\n const int R = int(matrix.size()), C = int(matrix[0].size());\n\t\tint the_sum = 0;\n\n for (int r=0; r<R; r++) {\n for (int c=0; c<C; c++) {\n\t\t\t\tthe_sum += int(abs(matrix[r][c]));\n if (c>0) matrix[r][c] += matrix[r][c-1];\n }\n }\n\n\t\tif (target > the_sum) return 0;\n\t\tif (target < -the_sum)return 0;\n \n for (int r=0; r<R; r++) {\n for (int c=0; c<C; c++) {\n if (r>0) matrix[r][c] += matrix[r-1][c];\n }\n }\n \n if (0) {\n for (int r=0; r<R; r++) {\n for (int c=0; c<C; c++) {\n printf("%d ", matrix[r][c]);\n }\n printf("\\n");\n }\n }\n \n int ret = 0;\n\n\t\tconst bool SLOW = false;\n\t\tif (SLOW) {\n\t\t\tfor (int r0=0; r0<R; r0++) {\n\t\t\t\tfor (int c0=0; c0<C; c0++) {\n\t\t\t\t\tfor (int r1=r0; r1<R; r1++) {\n\t\t\t\t\t\tfor (int c1=c0; c1<C; c1++) {\n\t\t\t\t\t\t\tint x = matrix[r1][c1];\n\t\t\t\t\t\t\tif (r0>0) x -= matrix[r0-1][c1];\n\t\t\t\t\t\t\tif (c0>0) x -= matrix[r1][c0-1];\n\t\t\t\t\t\t\tif (r0>0 && c0>0) x += matrix[r0-1][c0-1];\n\t\t\t\t\t\t\t//printf("[%d,%d,%d,%d] = %d\\n", r0,c0,r1,c1,x);\n\t\t\t\t\t\t\tif (x == target) {\n\t\t\t\t\t\t\t\tret++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor (int c0 = 0; c0 < C; c0 ++) {\n\t\t\t\tfor (int c1 = c0; c1 < C; c1 ++) {\n\t\t\t\t\tunordered_map<int, int> prefix_sums;\n\t\t\t\t\tfor (int r=0; r<R; r++) {\n\t\t\t\t\t\tint curr = matrix[r][c1];\n\t\t\t\t\t\tif (c0 > 0) curr -= matrix[r][c0-1];\n\t\t\t\t\n\t\t\t\t\t\tint key = -(target - curr);\n\t\t\t\t\t\tif (prefix_sums.find(key) != prefix_sums.end()) {\n\t\t\t\t\t\t\tret += prefix_sums[key];\n\t\t\t\t\t\t}\n//\t\t\t\t\t\tprintf("Cols[%d,%d] Rows[0,%d] sum=%d, key=%d\\n", c0, c1, r, curr, key);\n\t\t\t\t\t\tif (curr == target) ret ++;\n\n\t\t\t\t\t\tprefix_sums[curr] ++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n return ret;\n }\n};\n\n```\n
3
0
[]
1
number-of-submatrices-that-sum-to-target
Rust | Prefix Sum | simple solution
rust-prefix-sum-simple-solution-by-user7-ibec
Complexity\n- Time complexity: O(n^4)\n\n- Space complexity: O(n^2)\n\n# Code\n\nimpl Solution {\n pub fn num_submatrix_sum_target(matrix: Vec<Vec<i32>>, tar
user7454af
NORMAL
2024-06-23T03:48:20.702773+00:00
2024-06-23T03:48:20.702802+00:00
8
false
# Complexity\n- Time complexity: $$O(n^4)$$\n\n- Space complexity: $$O(n^2)$$\n\n# Code\n```\nimpl Solution {\n pub fn num_submatrix_sum_target(matrix: Vec<Vec<i32>>, target: i32) -> i32 {\n let (m, n) = (matrix.len(), matrix[0].len());\n let mut psum = vec![vec![0; n+1]; m+1];\n for i in 0..m {\n for j in 0..n {\n psum[i+1][j+1] = matrix[i][j] + psum[i+1][j] + psum[i][j+1] - psum[i][j];\n }\n }\n let mut ans = 0;\n for x_bottom in 1..=m {\n for y_bottom in 1..=n {\n let psum_bottom = psum[x_bottom][y_bottom];\n for x_top in 1..=x_bottom {\n let diff1 = psum[x_top-1][y_bottom];\n for y_top in 1..=y_bottom {\n if psum_bottom - diff1 - psum[x_bottom][y_top-1] + psum[x_top-1][y_top-1] == target {\n ans += 1;\n }\n }\n }\n }\n }\n ans\n }\n}\n```
2
0
['Rust']
0
number-of-submatrices-that-sum-to-target
2D Prefix Sum Problem
2d-prefix-sum-problem-by-zzzcxh-sg4d
Approach\n Describe your approach to solving the problem. \n1. Compute 2D prefix sum\n2. Reduce to 1D subarray problem\n\n# Complexity\n- Time complexity: O(mmn
zzzcxh
NORMAL
2024-01-29T19:17:01.420234+00:00
2024-01-29T19:17:01.420263+00:00
61
false
# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Compute 2D prefix sum\n2. Reduce to 1D subarray problem\n\n# Complexity\n- Time complexity: O(mmn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n\n# Code\n```\nclass Solution {\n public int numSubmatrixSumTarget(int[][] matrix, int target) {\n int m = matrix.length;\n int n = matrix[0].length;\n\n // step1 : calculate 2d prefix sum\n int[][] preSum = new int[m+1][n+1];\n for (int i = 1; i <= m;i++) {\n\t\t for (int j = 1;j <= n;j++){\n\t\t\t\tpreSum[i][j] = preSum[i-1][j] + preSum[i][j-1] + matrix[i-1][j-1] - preSum[i-1][j-1];\n\t\t }\n }\n\n Map<Integer, Integer> map = new HashMap<>();\n int count = 0;\n // step2: reduce this 2d problem to 1d\n for (int i = 1; i <= m; i++) {\n for (int j = i; j <= m; j++) {\n // consider every fixed row pair, so we need a new map each time\n // treat it a 1d array since the row is fixed, the only var is column\n map.clear();\n map.put(0, 1);\n for (int k = 1; k <= n; k++) {\n // current prefix sum\n int curSum = preSum[j][k] - preSum[i - 1][k];\n\n // subarray which sums up to (curSum - target)\n count += map.getOrDefault(curSum - target, 0);\n\n // add current sum into map\n map.put(curSum, map.getOrDefault(curSum, 0) + 1);\n }\n }\n }\n return count;\n }\n}\n```
2
0
['Java']
0
number-of-submatrices-that-sum-to-target
[Java] ✨✨✨ Prefix sum 2D, explained with pictures
java-prefix-sum-2d-explained-with-pictur-dpka
Intuition\nWe need to have a quick way to understand what is the sum for the given matrix. We can start from prefix sum 2D (in matrix), where each element (i, j
kesshb
NORMAL
2024-01-28T12:05:20.677633+00:00
2024-01-28T12:05:20.677669+00:00
243
false
# Intuition\nWe need to have a quick way to understand what is the sum for the given matrix. We can start from **prefix sum 2D** (in matrix), where each element (i, j) will hold sum for all elements in matrix for x from 0 to i, and y from 0 to j.\n\nPrefix sum matrix will be calculated in a loop using result of previous elements:\n![image](https://live.staticflickr.com/65535/53492870323_1f0819695b_n.jpg)\n\nSo we will use formula:\n$$Sum(i, j) = matrix(i, j) + sum(i, j-1) + sum(i-1, j) - sum(i-1, j-1)$$\nWe are subtracting sum(i-1,j-1) because it\'s counted twice from (i, j-1) and (i-1, j).\n\nBased on this results we can calculate sum for **any** matrix, not necessarily starting from x=0 and y=0:\n![image](https://live.staticflickr.com/65535/53493036004_61fdd3f1e9.jpg)\ni.e.:\n$$sum(x1,y1,x2,y2) = sum(x2,y2) - sum(x2,y1-1) - sum(x1-1, y2) + sum (x1-1,y1-1)$$\n\nIn case if x1-1 or y1-1 become negative - we just use 0 instead of matrix value.\n\n# Approach\n1) Calculate matrix prefix sum 2D array - see above approach.\n2) Fix y1 = 0 - it will be always 0 in our solution (i.e. we will always start from 1st column).\n3) For each x1 fix x2 values one by one (i.e. we fix set of rows, e.g. 0,1, then 0,1,2, then 0,1,2,3, etc., and same for other x1, e.g. 2,3,4 -> 2,3,4,5, etc.). Main calculations will happen then for fixed x1, x2, y1;\n4) Define Map<Integer, Integer> - it will store number of occurrencies of any specific sum. Init count = 0;\n5) Iterate y2 from 0 to n-1. \nFor each y2:\n- calculate matrix sum - see intution 2nd picture and formula;\n- if sum == target, then increment count by 1 (we found matrix resulting in target).\n- Add to count the number of occurencies so far of the **sum - target** values. Why do we do this? Let\'s imagine we fixed x1, x2, y1, and increment y2 from 0 to n-1. Let\'s assume target = 3. We get sums: 0, 4, 5, 7, 8, 9. So far no sums = target = 3. Let\'s look at sums 4 and 7. If we decrement 4 from 7 - we will get 3. It means if we take y1 = 2 and y2 = 3 - we will get sum equal not to 7, but to 7-4=3 (as we removed left part of the matrix). That\'s basically how prefix sum works. Same for 5 vs 8 - for y1 = 3 and y2 = 4 we would get sum=3, unlike 8 that we\'re getting for y1 = 0.\n- Add current sum to the map for the next iterations.\n6) Clean prefix map on each changing x1 and x2 - we will start from a scratch for different boundaries.\n7) After all iterations return count.\n\n# Complexity\nM - number of rows;\nN - number of columns;\n\n- Time complexity:\n$$O(N*M^2)$$\n\n- Space complexity:\n$$O(M*N)$$\n\n# Code\n```\nclass Solution {\n\n private int m;\n private int n;\n \n public int numSubmatrixSumTarget(int[][] matrix, int target) {\n m = matrix.length;\n n = matrix[0].length;\n int[][] sumMatrix = prepareSumMatrix(matrix);\n int count = 0;\n Map<Integer, Integer> countsMap = new HashMap<>();\n for (int x1 = 0; x1 < m; x1++) {\n countsMap.clear();\n for (int k1 = 0; x1 + k1 < m; k1++) {\n int x2 = x1 + k1;\n countsMap.clear();\n for (int y2 = 0; y2 < n; y2++) {\n int currSum = matrixSumFor(sumMatrix, x1, 0, x2, y2);\n if (currSum == target) { \n count++;\n }\n count += countsMap.getOrDefault(currSum - target, 0);\n countsMap.put(currSum, countsMap.getOrDefault(currSum, 0) + 1);\n }\n }\n }\n return count;\n }\n\n private int matrixSumFor(int[][] sumMatrix, int x1, int y1, int x2, int y2) {\n return sumMatrix[x2][y2] - (x1 == 0? 0 : sumMatrix[x1 - 1][y2]) - (y1 == 0? 0 : sumMatrix[x2][y1-1]) \n + (x1 == 0 || y1 == 0 ? 0 : sumMatrix[x1-1][y1-1]);\n }\n\n private int[][] prepareSumMatrix(int[][] matrix) {\n int[][] sum = new int[m][n];\n sum[0][0] = matrix[0][0];\n for (int i = 1; i < m; i++) {\n sum[i][0] = sum[i-1][0] + matrix[i][0];\n }\n for (int j = 1; j < n; j++) {\n sum[0][j] = sum[0][j-1] + matrix[0][j];\n }\n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n sum[i][j] = matrix[i][j] + sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1];\n }\n }\n return sum;\n }\n}\n```
2
0
['Java']
0
number-of-submatrices-that-sum-to-target
C# Solution for Number of Submatrices That Sum To Target Problem
c-solution-for-number-of-submatrices-tha-uvmy
Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind this solution is to use prefix sums and a hashmap to efficiently f
Aman_Raj_Sinha
NORMAL
2024-01-28T09:33:20.176155+00:00
2024-01-28T09:33:20.176178+00:00
67
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this solution is to use prefix sums and a hashmap to efficiently find submatrices with the target sum. By iterating over all possible pairs of columns and treating the problem as a one-dimensional array problem along the rows, the solution aims to optimize the counting process.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tPrecompute the prefix sum for each row in the matrix, similar to the Java solution.\n2.\tIterate over all possible pairs of columns (left and right) to form a potential submatrix.\n3.\tFor each pair of columns, iterate over all rows and calculate the sum of the submatrix between those columns.\n4.\tUse a dictionary (Dictionary<int, int>) to keep track of the prefix sums encountered so far. Update the dictionary as you iterate over the rows.\n5.\tCheck if the current prefix sum minus the target is present in the dictionary. If yes, update the count accordingly.\n6.\tReturn the final count as the result.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nLet m be the number of rows and n be the number of columns. The double nested loops over columns and rows contribute O(n^2 * m) time complexity. The dictionary operations inside the loops take O(1) time. Overall, the time complexity is O(n^2 * m).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(m) for the dictionary used to store prefix sums. Additionally, there are some constant space variables. Therefore, the overall space complexity is O(m). The space complexity is kept low by using a dictionary to store prefix sums instead of a nested hashm\n\n# Code\n```\npublic class Solution {\n public int NumSubmatrixSumTarget(int[][] matrix, int target) {\n int m = matrix.Length;\n int n = matrix[0].Length;\n int result = 0;\n\n // Precompute the prefix sum for each row\n for (int i = 0; i < m; i++) {\n for (int j = 1; j < n; j++) {\n matrix[i][j] += matrix[i][j - 1];\n }\n }\n\n // Iterate over all possible column pairs\n for (int left = 0; left < n; left++) {\n for (int right = left; right < n; right++) {\n int currentSum = 0;\n Dictionary<int, int> prefixSumCount = new Dictionary<int, int>();\n prefixSumCount[0] = 1;\n\n // Iterate over all rows to calculate the submatrix sum\n for (int row = 0; row < m; row++) {\n int rowSum = matrix[row][right] - (left > 0 ? matrix[row][left - 1] : 0);\n currentSum += rowSum;\n\n // Check if there is a submatrix with the target sum\n if (prefixSumCount.ContainsKey(currentSum - target)) {\n result += prefixSumCount[currentSum - target];\n }\n\n // Update the prefix sum count\n if (prefixSumCount.ContainsKey(currentSum)) {\n prefixSumCount[currentSum]++;\n } else {\n prefixSumCount[currentSum] = 1;\n }\n }\n }\n }\n\n return result;\n }\n}\n```
2
0
['C#']
0
number-of-submatrices-that-sum-to-target
C++ || Python3 || Hash Table & Prefix Sum || Комментарии на русском || RUS_comments
c-python3-hash-table-prefix-sum-kommenta-282s
Intuition\n Describe your first thoughts on how to solve this problem. \n\u0417\u0430\u0434\u0430\u0447\u0430 "Number of Submatrices That Sum to Target" \u043F\
bakhtiyarzbj
NORMAL
2024-01-28T07:25:52.915914+00:00
2024-01-28T07:26:21.690316+00:00
107
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\u0417\u0430\u0434\u0430\u0447\u0430 "Number of Submatrices That Sum to Target" \u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u044F\u0435\u0442 \u0441\u043E\u0431\u043E\u0439 \u0438\u043D\u0442\u0435\u0440\u0435\u0441\u043D\u0443\u044E \u0437\u0430\u0434\u0430\u0447\u0443 \u043D\u0430 \u0440\u0430\u0431\u043E\u0442\u0443 \u0441 \u043C\u0430\u0442\u0440\u0438\u0446\u0430\u043C\u0438 \u0438 \u043F\u043E\u0438\u0441\u043A\u043E\u043C \u043F\u043E\u0434\u043C\u0430\u0442\u0440\u0438\u0446. \u0415\u0435 \u0440\u0435\u0448\u0435\u043D\u0438\u0435 \u0442\u0440\u0435\u0431\u0443\u0435\u0442 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u043D\u043E\u0433\u043E \u043F\u043E\u0434\u0445\u043E\u0434\u0430, \u0432 \u0434\u0430\u043D\u043D\u043E\u043C \u0441\u043B\u0443\u0447\u0430\u0435, \u043F\u0440\u0435\u0444\u0438\u043A\u0441\u043D\u044B\u0445 \u0441\u0443\u043C\u043C.\n\u0421\u043C\u044B\u0441\u043B \u0437\u0430\u0434\u0430\u0447\u0438 \u0437\u0430\u043A\u043B\u044E\u0447\u0430\u0435\u0442\u0441\u044F \u0432 \u0442\u043E\u043C, \u0447\u0442\u043E\u0431\u044B \u044D\u0444\u0444\u0435\u043A\u0442\u0438\u0432\u043D\u043E \u043D\u0430\u0445\u043E\u0434\u0438\u0442\u044C \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u043F\u043E\u0434\u043C\u0430\u0442\u0440\u0438\u0446 \u0432 \u0437\u0430\u0434\u0430\u043D\u043D\u043E\u0439 \u043C\u0430\u0442\u0440\u0438\u0446\u0435, \u0441\u0443\u043C\u043C\u0430 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432 \u043A\u043E\u0442\u043E\u0440\u044B\u0445 \u0440\u0430\u0432\u043D\u0430 \u043F\u0440\u0435\u0434\u043E\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u043D\u043E\u043C\u0443 \u0446\u0435\u043B\u0435\u0432\u043E\u043C\u0443 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044E. \u042D\u0442\u0430 \u0437\u0430\u0434\u0430\u0447\u0430 \u043C\u043E\u0436\u0435\u0442 \u0438\u043C\u0435\u0442\u044C \u043F\u0440\u0430\u043A\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0435 \u043F\u0440\u0438\u043C\u0435\u043D\u0435\u043D\u0438\u0435 \u0432 \u043E\u0431\u043B\u0430\u0441\u0442\u044F\u0445, \u0441\u0432\u044F\u0437\u0430\u043D\u043D\u044B\u0445 \u0441 \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u043E\u0439 \u0434\u0430\u043D\u043D\u044B\u0445 \u0438 \u0430\u043D\u0430\u043B\u0438\u0437\u043E\u043C, \u043D\u0430\u043F\u0440\u0438\u043C\u0435\u0440, \u0432 \u043A\u043E\u043C\u043F\u044C\u044E\u0442\u0435\u0440\u043D\u043E\u043C \u0437\u0440\u0435\u043D\u0438\u0438, \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0435 \u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0439, \u0438\u043B\u0438 \u0430\u043D\u0430\u043B\u0438\u0437\u0435 \u0434\u0430\u043D\u043D\u044B\u0445 \u0434\u043B\u044F \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u044F \u043E\u0431\u043B\u0430\u0441\u0442\u0435\u0439 \u0441 \u0437\u0430\u0434\u0430\u043D\u043D\u043E\u0439 \u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u043E\u0439.\n\u0420\u0435\u0448\u0435\u043D\u0438\u0435 \u0442\u0430\u043A\u0438\u0445 \u0437\u0430\u0434\u0430\u0447 \u043C\u043E\u0436\u0435\u0442 \u0431\u044B\u0442\u044C \u043F\u043E\u043B\u0435\u0437\u043D\u044B\u043C \u0432 \u0440\u0430\u0437\u043B\u0438\u0447\u043D\u044B\u0445 \u043E\u0431\u043B\u0430\u0441\u0442\u044F\u0445, \u0433\u0434\u0435 \u043D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E \u044D\u0444\u0444\u0435\u043A\u0442\u0438\u0432\u043D\u043E \u043D\u0430\u0445\u043E\u0434\u0438\u0442\u044C \u0438 \u0430\u043D\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u044B \u0432 \u0431\u043E\u043B\u044C\u0448\u0438\u0445 \u043E\u0431\u044A\u0435\u043C\u0430\u0445 \u0434\u0430\u043D\u043D\u044B\u0445. \u0422\u0430\u043A\u0438\u0435 \u0437\u0430\u0434\u0430\u0447\u0438 \u0442\u0440\u0435\u0431\u0443\u044E\u0442 \u0440\u0430\u0437\u0440\u0430\u0431\u043E\u0442\u043A\u0438 \u044D\u0444\u0444\u0435\u043A\u0442\u0438\u0432\u043D\u044B\u0445 \u0430\u043B\u0433\u043E\u0440\u0438\u0442\u043C\u043E\u0432 \u0434\u043B\u044F \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438 \u0438 \u0430\u043D\u0430\u043B\u0438\u0437\u0430 \u043C\u0430\u0442\u0440\u0438\u0446, \u0447\u0442\u043E \u0434\u0435\u043B\u0430\u0435\u0442 \u0438\u0445 \u0438\u043D\u0442\u0435\u0440\u0435\u0441\u043D\u044B\u043C\u0438 \u0434\u043B\u044F \u0438\u0437\u0443\u0447\u0435\u043D\u0438\u044F \u0438 \u0440\u0435\u0448\u0435\u043D\u0438\u044F.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\u0417\u0430\u0434\u0430\u0447\u0430 \u0437\u0430\u043A\u043B\u044E\u0447\u0430\u0435\u0442\u0441\u044F \u0432 \u043F\u043E\u0434\u0441\u0447\u0435\u0442\u0435 \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u043F\u043E\u0434\u043C\u0430\u0442\u0440\u0438\u0446 \u0432 \u043C\u0430\u0442\u0440\u0438\u0446\u0435, \u0441\u0443\u043C\u043C\u0430 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432 \u043A\u043E\u0442\u043E\u0440\u044B\u0445 \u0440\u0430\u0432\u043D\u0430 \u0446\u0435\u043B\u0435\u0432\u043E\u043C\u0443 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044E. \u0414\u043B\u044F \u0440\u0435\u0448\u0435\u043D\u0438\u044F \u0434\u0430\u043D\u043D\u043E\u0439 \u0437\u0430\u0434\u0430\u0447\u0438 \u043C\u044B \u0431\u0443\u0434\u0435\u043C \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C \u043C\u0435\u0442\u043E\u0434 \u043F\u0440\u0435\u0444\u0438\u043A\u0441\u043D\u044B\u0445 \u0441\u0443\u043C\u043C, \u043A\u043E\u0442\u043E\u0440\u044B\u0439 \u043F\u043E\u0437\u0432\u043E\u043B\u044F\u0435\u0442 \u0431\u044B\u0441\u0442\u0440\u043E \u0432\u044B\u0447\u0438\u0441\u043B\u0438\u0442\u044C \u0441\u0443\u043C\u043C\u0443 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432 \u0432 \u043F\u0440\u044F\u043C\u043E\u0443\u0433\u043E\u043B\u044C\u043D\u043E\u0439 \u043F\u043E\u0434\u043C\u0430\u0442\u0440\u0438\u0446\u0435.\n**\u041F\u0440\u0435\u0444\u0438\u043A\u0441\u043D\u044B\u0435 \u0441\u0443\u043C\u043C\u044B \u043F\u043E \u0441\u0442\u0440\u043E\u043A\u0430\u043C:** \u041F\u0440\u0435\u0436\u0434\u0435 \u0432\u0441\u0435\u0433\u043E, \u043C\u044B \u0432\u044B\u0447\u0438\u0441\u043B\u044F\u0435\u043C \u043F\u0440\u0435\u0444\u0438\u043A\u0441\u043D\u044B\u0435 \u0441\u0443\u043C\u043C\u044B \u0434\u043B\u044F \u043A\u0430\u0436\u0434\u043E\u0439 \u0441\u0442\u0440\u043E\u043A\u0438 \u043C\u0430\u0442\u0440\u0438\u0446\u044B. \u042D\u0442\u043E \u0434\u0435\u043B\u0430\u0435\u0442\u0441\u044F \u0434\u043B\u044F \u0443\u0441\u043A\u043E\u0440\u0435\u043D\u0438\u044F \u0432\u044B\u0447\u0438\u0441\u043B\u0435\u043D\u0438\u044F \u0441\u0443\u043C\u043C\u044B \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432 \u0432 \u043F\u0440\u044F\u043C\u043E\u0443\u0433\u043E\u043B\u044C\u043D\u044B\u0445 \u043F\u043E\u0434\u043C\u0430\u0442\u0440\u0438\u0446\u0430\u0445. \u041A\u0430\u0436\u0434\u044B\u0439 \u044D\u043B\u0435\u043C\u0435\u043D\u0442 matrix[i][j] \u0432 \u043C\u0430\u0442\u0440\u0438\u0446\u0435 \u0431\u0443\u0434\u0435\u0442 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C \u0441\u0443\u043C\u043C\u0443 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432 \u043E\u0442 matrix[i][0] \u0434\u043E matrix[i][j].\n**\u041F\u0435\u0440\u0435\u0431\u043E\u0440 \u0441\u0442\u043E\u043B\u0431\u0446\u043E\u0432:** \u0417\u0430\u0442\u0435\u043C \u043C\u044B \u043F\u0435\u0440\u0435\u0431\u0438\u0440\u0430\u0435\u043C \u0432\u0441\u0435 \u0432\u043E\u0437\u043C\u043E\u0436\u043D\u044B\u0435 \u043F\u0430\u0440\u044B \u0441\u0442\u043E\u043B\u0431\u0446\u043E\u0432 col1 \u0438 col2 (\u0433\u0434\u0435 col1 <= col2).\n**\u0412\u044B\u0447\u0438\u0441\u043B\u0435\u043D\u0438\u0435 \u0441\u0443\u043C\u043C\u044B \u043F\u043E\u0434\u043C\u0430\u0442\u0440\u0438\u0446\u044B:** \u0414\u043B\u044F \u043A\u0430\u0436\u0434\u043E\u0439 \u043F\u0430\u0440\u044B \u0441\u0442\u043E\u043B\u0431\u0446\u043E\u0432 \u0438\u0434\u0435\u043C \u043F\u043E \u0441\u0442\u0440\u043E\u043A\u0430\u043C \u0438 \u0432\u044B\u0447\u0438\u0441\u043B\u044F\u0435\u043C \u0441\u0443\u043C\u043C\u0443 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432 \u0432 \u043F\u043E\u0434\u043C\u0430\u0442\u0440\u0438\u0446\u0435, \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u044F \u043F\u0440\u0435\u0444\u0438\u043A\u0441\u043D\u044B\u0435 \u0441\u0443\u043C\u043C\u044B. \u0415\u0441\u043B\u0438 col1 == 0, \u0442\u043E \u0441\u0443\u043C\u043C\u0430 \u0440\u0430\u0432\u043D\u0430 matrix[row][col2]. \u0412 \u043F\u0440\u043E\u0442\u0438\u0432\u043D\u043E\u043C \u0441\u043B\u0443\u0447\u0430\u0435, \u0441\u0443\u043C\u043C\u0430 \u0440\u0430\u0432\u043D\u0430 matrix[row][col2] - matrix[row][col1 - 1].\n**\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435 \u0445\u044D\u0448-\u0442\u0430\u0431\u043B\u0438\u0446\u044B \u0434\u043B\u044F \u043E\u0442\u0441\u043B\u0435\u0436\u0438\u0432\u0430\u043D\u0438\u044F \u0441\u0443\u043C\u043C:** \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u043C \u0445\u044D\u0448-\u0442\u0430\u0431\u043B\u0438\u0446\u0443 (unordered_map \u0432 C++), \u0447\u0442\u043E\u0431\u044B \u043E\u0442\u0441\u043B\u0435\u0436\u0438\u0432\u0430\u0442\u044C \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0432\u0441\u0442\u0440\u0435\u0447\u0435\u043D\u043D\u044B\u0445 \u0441\u0443\u043C\u043C \u0432 \u0442\u0435\u043A\u0443\u0449\u0435\u043C \u0441\u0442\u043E\u043B\u0431\u0446\u043E\u0432\u043E\u043C \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D\u0435.\n**\u041F\u043E\u0434\u0441\u0447\u0435\u0442 \u043F\u043E\u0434\u043C\u0430\u0442\u0440\u0438\u0446:** \u041F\u043E\u0441\u043B\u0435 \u0432\u044B\u0447\u0438\u0441\u043B\u0435\u043D\u0438\u044F \u0441\u0443\u043C\u043C\u044B \u0442\u0435\u043A\u0443\u0449\u0435\u0439 \u043F\u043E\u0434\u043C\u0430\u0442\u0440\u0438\u0446\u044B, \u043F\u0440\u043E\u0432\u0435\u0440\u044F\u0435\u043C, \u0440\u0430\u0432\u043D\u0430 \u043B\u0438 \u044D\u0442\u0430 \u0441\u0443\u043C\u043C\u0430 \u0446\u0435\u043B\u0435\u0432\u043E\u043C\u0443 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044E. \u0415\u0441\u043B\u0438 \u0434\u0430, \u0443\u0432\u0435\u043B\u0438\u0447\u0438\u0432\u0430\u0435\u043C \u043E\u0431\u0449\u0438\u0439 \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442. \u0415\u0441\u043B\u0438 \u0441\u0443\u043C\u043C\u0430 \u043C\u0438\u043D\u0443\u0441 \u0446\u0435\u043B\u0435\u0432\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0443\u0436\u0435 \u0432\u0441\u0442\u0440\u0435\u0447\u0430\u043B\u0430\u0441\u044C, \u0443\u0432\u0435\u043B\u0438\u0447\u0438\u0432\u0430\u0435\u043C \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442 \u043D\u0430 \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0432\u0441\u0442\u0440\u0435\u0447\u0435\u043D\u043D\u044B\u0445 \u0442\u0430\u043A\u0438\u0445 \u0441\u0443\u043C\u043C.\n# Complexity\n- Time complexity: \u0412\u043D\u0435\u0448\u043D\u0438\u0439 \u0446\u0438\u043A\u043B \u043F\u0435\u0440\u0435\u0431\u043E\u0440\u0430 \u043F\u0430\u0440 \u0441\u0442\u043E\u043B\u0431\u0446\u043E\u0432 \u0432\u044B\u043F\u043E\u043B\u043D\u044F\u0435\u0442\u0441\u044F \u0437\u0430 $$O(n^2)$$. \u0412\u043D\u0443\u0442\u0440\u0435\u043D\u043D\u0438\u0439 \u0446\u0438\u043A\u043B \u043F\u0435\u0440\u0435\u0431\u043E\u0440\u0430 \u0441\u0442\u0440\u043E\u043A \u0432\u044B\u043F\u043E\u043B\u043D\u044F\u0435\u0442\u0441\u044F \u0437\u0430 $$O(m)$$, \u0433\u0434\u0435 $$m$$ - \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0441\u0442\u0440\u043E\u043A \u0432 \u043C\u0430\u0442\u0440\u0438\u0446\u0435. \u0412 \u043A\u0430\u0436\u0434\u043E\u043C \u0448\u0430\u0433\u0435 \u0432\u043D\u0443\u0442\u0440\u0435\u043D\u043D\u0435\u0433\u043E \u0446\u0438\u043A\u043B\u0430 \u043C\u044B \u0432\u044B\u0447\u0438\u0441\u043B\u044F\u0435\u043C \u043F\u0440\u0435\u0444\u0438\u043A\u0441\u043D\u044B\u0435 \u0441\u0443\u043C\u043C\u044B \u0434\u043B\u044F \u043A\u0430\u0436\u0434\u043E\u0439 \u0441\u0442\u0440\u043E\u043A\u0438 \u0438 \u043E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u043C \u0445\u044D\u0448-\u0442\u0430\u0431\u043B\u0438\u0446\u0443. \u041F\u043E\u0438\u0441\u043A \u0441\u0443\u043C\u043C\u044B \u0432 \u0445\u044D\u0448-\u0442\u0430\u0431\u043B\u0438\u0446\u0435 \u0432\u044B\u043F\u043E\u043B\u043D\u044F\u0435\u0442\u0441\u044F \u0437\u0430 $$O(1)$$.\n\u0422\u0430\u043A\u0438\u043C \u043E\u0431\u0440\u0430\u0437\u043E\u043C, \u043E\u0431\u0449\u0430\u044F \u0432\u0440\u0435\u043C\u0435\u043D\u043D\u0430\u044F \u0441\u043B\u043E\u0436\u043D\u043E\u0441\u0442\u044C \u0440\u0430\u0432\u043D\u0430 $$O(n^2 * m)$$.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: \u0414\u043B\u044F \u0445\u0440\u0430\u043D\u0435\u043D\u0438\u044F \u043F\u0440\u0435\u0444\u0438\u043A\u0441\u043D\u044B\u0445 \u0441\u0443\u043C\u043C \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F $$O(m * n)$$ \u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0439 \u043F\u0430\u043C\u044F\u0442\u0438 (\u0440\u0430\u0437\u043C\u0435\u0440 \u043C\u0430\u0442\u0440\u0438\u0446\u044B). \u0425\u044D\u0448-\u0442\u0430\u0431\u043B\u0438\u0446\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u0442\u0441\u044F \u0434\u043B\u044F \u043E\u0442\u0441\u043B\u0435\u0436\u0438\u0432\u0430\u043D\u0438\u044F \u0441\u0443\u043C\u043C \u0438 \u0442\u0440\u0435\u0431\u0443\u0435\u0442 $$O(n)$$ \u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0439 \u043F\u0430\u043C\u044F\u0442\u0438.\n\u0422\u0430\u043A\u0438\u043C \u043E\u0431\u0440\u0430\u0437\u043E\u043C, \u043E\u0431\u0449\u0430\u044F \u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432\u0435\u043D\u043D\u0430\u044F \u0441\u043B\u043E\u0436\u043D\u043E\u0441\u0442\u044C \u0440\u0430\u0432\u043D\u0430 $$O(m * n + n)$$.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n![image.png](https://assets.leetcode.com/users/images/e80ab198-3e76-41a9-a055-123a442936fc_1706426731.7796502.png)\n\n# C++\n```\n#include <vector>\n#include <unordered_map>\n\nusing namespace std;\n\nclass Solution {\npublic:\n int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {\n int m = matrix.size();\n int n = matrix[0].size();\n\n // \u0420\u0430\u0441\u0441\u0447\u0438\u0442\u044B\u0432\u0430\u0435\u043C \u043F\u0440\u0435\u0444\u0438\u043A\u0441\u043D\u044B\u0435 \u0441\u0443\u043C\u043C\u044B \u0434\u043B\u044F \u043A\u0430\u0436\u0434\u043E\u0439 \u0441\u0442\u0440\u043E\u043A\u0438\n for (int i = 0; i < m; ++i) {\n for (int j = 1; j < n; ++j) {\n matrix[i][j] += matrix[i][j - 1];\n }\n }\n\n int result = 0;\n\n // \u041F\u0435\u0440\u0435\u0431\u0438\u0440\u0430\u0435\u043C \u0432\u0441\u0435 \u0432\u043E\u0437\u043C\u043E\u0436\u043D\u044B\u0435 \u043F\u0430\u0440\u044B \u0441\u0442\u043E\u043B\u0431\u0446\u043E\u0432\n for (int col1 = 0; col1 < n; ++col1) {\n for (int col2 = col1; col2 < n; ++col2) {\n unordered_map<int, int> counter;\n int current_sum = 0;\n\n // \u041F\u0435\u0440\u0435\u0431\u0438\u0440\u0430\u0435\u043C \u0432\u0441\u0435 \u0441\u0442\u0440\u043E\u043A\u0438\n for (int row = 0; row < m; ++row) {\n // \u0420\u0430\u0441\u0441\u0447\u0438\u0442\u044B\u0432\u0430\u0435\u043C \u0441\u0443\u043C\u043C\u0443 \u043F\u043E\u0434\u043C\u0430\u0442\u0440\u0438\u0446\u044B, \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u044F \u043F\u0440\u0435\u0444\u0438\u043A\u0441\u043D\u044B\u0435 \u0441\u0443\u043C\u043C\u044B\n if (col1 == 0) {\n current_sum += matrix[row][col2];\n } else {\n current_sum += matrix[row][col2] - matrix[row][col1 - 1];\n }\n\n // \u0415\u0441\u043B\u0438 current_sum - target \u0435\u0441\u0442\u044C \u0432 \u0441\u0447\u0435\u0442\u0447\u0438\u043A\u0435, \u0434\u043E\u0431\u0430\u0432\u043B\u044F\u0435\u043C \u0435\u0433\u043E \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u043A \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0443\n if (current_sum == target) {\n result++;\n }\n\n if (counter.find(current_sum - target) != counter.end()) {\n result += counter[current_sum - target];\n }\n\n // \u041E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u043C \u0441\u0447\u0435\u0442\u0447\u0438\u043A \u0442\u0435\u043A\u0443\u0449\u0435\u0439 \u0441\u0443\u043C\u043C\u043E\u0439\n counter[current_sum]++;\n }\n }\n }\n\n return result;\n }\n};\n```\n![image.png](https://assets.leetcode.com/users/images/29492588-39a0-429d-b4ec-314a444a6c57_1706426707.4036531.png)\n\n# Python\n```\nfrom typing import List\n\nclass Solution:\n def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:\n m, n = len(matrix), len(matrix[0])\n\n # \u0420\u0430\u0441\u0441\u0447\u0438\u0442\u044B\u0432\u0430\u0435\u043C \u043F\u0440\u0435\u0444\u0438\u043A\u0441\u043D\u044B\u0435 \u0441\u0443\u043C\u043C\u044B \u0434\u043B\u044F \u043A\u0430\u0436\u0434\u043E\u0439 \u0441\u0442\u0440\u043E\u043A\u0438\n for i in range(m):\n for j in range(1, n):\n matrix[i][j] += matrix[i][j - 1]\n\n result = 0\n\n # \u041F\u0435\u0440\u0435\u0431\u0438\u0440\u0430\u0435\u043C \u0432\u0441\u0435 \u0432\u043E\u0437\u043C\u043E\u0436\u043D\u044B\u0435 \u043F\u0430\u0440\u044B \u0441\u0442\u043E\u043B\u0431\u0446\u043E\u0432\n for col1 in range(n):\n for col2 in range(col1, n):\n counter = {0: 1}\n current_sum = 0\n\n # \u041F\u0435\u0440\u0435\u0431\u0438\u0440\u0430\u0435\u043C \u0432\u0441\u0435 \u0441\u0442\u0440\u043E\u043A\u0438\n for row in range(m):\n # \u0420\u0430\u0441\u0441\u0447\u0438\u0442\u044B\u0432\u0430\u0435\u043C \u0441\u0443\u043C\u043C\u0443 \u043F\u043E\u0434\u043C\u0430\u0442\u0440\u0438\u0446\u044B, \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u044F \u043F\u0440\u0435\u0444\u0438\u043A\u0441\u043D\u044B\u0435 \u0441\u0443\u043C\u043C\u044B\n if col1 == 0:\n current_sum += matrix[row][col2]\n else:\n current_sum += matrix[row][col2] - matrix[row][col1 - 1]\n\n # \u0415\u0441\u043B\u0438 current_sum - target \u0435\u0441\u0442\u044C \u0432 \u0441\u0447\u0435\u0442\u0447\u0438\u043A\u0435, \u0434\u043E\u0431\u0430\u0432\u043B\u044F\u0435\u043C \u0435\u0433\u043E \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u043A \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0443\n if current_sum - target in counter:\n result += counter[current_sum - target]\n\n # \u041E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u043C \u0441\u0447\u0435\u0442\u0447\u0438\u043A \u0442\u0435\u043A\u0443\u0449\u0435\u0439 \u0441\u0443\u043C\u043C\u043E\u0439\n counter[current_sum] = counter.get(current_sum, 0) + 1\n\n return result\n```
2
0
['Array', 'Hash Table', 'Matrix', 'Prefix Sum', 'C++', 'Python3']
0
number-of-submatrices-that-sum-to-target
✅Easy C++ Solution Similar to Sub Array Sum
easy-c-solution-similar-to-sub-array-sum-fy9b
Intuition\n- Find prefix sum for each row.\n- Then find subarray sum for each pair of column and check if it\'s equals to the target or not.\n\n# Approach\n Des
sambit_2022
NORMAL
2024-01-28T02:03:02.675404+00:00
2024-01-28T02:05:20.687251+00:00
414
false
# Intuition\n- Find prefix sum for each row.\n- Then find subarray sum for each pair of column and check if it\'s equals to the target or not.\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\nint subarraySum(vector<int>& nums, int k) {\n\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n \n int cnt = 0, curr_sum = 0;\n unordered_map<int, int>mp;\n for(int i=0; i<nums.size(); i++)\n {\n curr_sum += nums[i];\n\n if(curr_sum == k)cnt++;\n if(mp.find(curr_sum - k) != mp.end())\n {\n cnt += mp[curr_sum - k];\n }\n\n mp[curr_sum]++;\n }\n\n return cnt;\n }\n\n \n int numSubmatrixSumTarget(vector<vector<int>>& mat, int target) {\n\n int count=0;\n int n = mat.size();\n int m = mat[0].size();\n\n for(int i=0; i<n; i++){\n\t\t\t\n vector<int> sum(m, 0);\n for(int j=i; j<n; j++){\n for(int k=0; k<m; k++){\n sum[k] += mat[j][k];\n }\n count += subarraySum(sum, target);\n }\n }\n \n return count;\n \n }\n};\n```
2
1
['Array', 'Hash Table', 'Matrix', 'Prefix Sum', 'C++']
0
number-of-submatrices-that-sum-to-target
Simple java code 79 ms beats 98.84 %
simple-java-code-79-ms-beats-9884-by-aro-7o6v
\n# Complexity\n- \n\n# Code\n\nclass Solution {\n public int numSubmatrixSumTarget(int[][] nums, int t) {\n int row=nums.length;\n int col=num
Arobh
NORMAL
2024-01-28T01:39:33.853798+00:00
2024-01-28T01:39:33.853816+00:00
45
false
\n# Complexity\n- \n![image.png](https://assets.leetcode.com/users/images/868fb304-6d7f-4d00-86fe-0fc186fe1cc2_1706405946.013867.png)\n# Code\n```\nclass Solution {\n public int numSubmatrixSumTarget(int[][] nums, int t) {\n int row=nums.length;\n int col=nums[0].length;\n int count=0;\n for(int i=0;i<row;i++) {\n int arr[]=new int[col];\n for(int j=i;j<row;j++) {\n for(int k=0;k<col;k++) {\n arr[k]+=nums[j][k];\n }\n for(int l=0;l<col;l++) {\n int sum=0;\n for(int r=l;r<col;r++) {\n sum+=arr[r];\n if(sum==t) {\n count++;\n }\n }\n }\n }\n }\n return count;\n }\n}\n```
2
1
['Array', 'Matrix', 'Prefix Sum', 'Java']
0
number-of-submatrices-that-sum-to-target
just a variant
just-a-variant-by-igormsc-thbe
Code\n\nclass Solution {\n fun numSubmatrixSumTarget(matrix: Array<IntArray>, target: Int): Int {\n val n = matrix.lastIndex\n val m = matrix.f
igormsc
NORMAL
2024-01-28T00:53:43.609747+00:00
2024-01-28T00:53:43.609767+00:00
55
false
# Code\n```\nclass Solution {\n fun numSubmatrixSumTarget(matrix: Array<IntArray>, target: Int): Int {\n val n = matrix.lastIndex\n val m = matrix.first().lastIndex\n val dp = Array(101) { IntArray(101) }.also { it[0][0] = matrix[0][0] }\n\n (1..n).forEach { dp[it][0] = matrix[it][0] + dp[it - 1][0] }\n (1..m).forEach { dp[0][it] = matrix[0][it] + dp[0][it - 1] }\n (1..n).forEach { i ->\n (1..m).forEach { j ->\n dp[i][j] = matrix[i][j] + dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1] } }\n\n return (0..n).sumOf { i ->\n (0..m).sumOf { j ->\n (i..n).sumOf { l ->\n (j..m).count { k ->\n target == dp[l][k] - (if (i > 0) dp[i - 1][k] else 0) - (if (j > 0) dp[l][j - 1] else 0) +\n (if (i > 0 && j > 0) dp[i - 1][j - 1] else 0) } } } }\n }\n}\n```
2
0
['Kotlin']
0
number-of-submatrices-that-sum-to-target
Concise Easy to Understand Intuition and Code
concise-easy-to-understand-intuition-and-l5cy
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nFor each pair of columns (i, j) from index i to j inclusive:\n\nCreate a
29anshuarya
NORMAL
2023-08-29T16:35:55.142873+00:00
2023-08-29T16:35:55.142905+00:00
340
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nFor each pair of columns (i, j) from index i to j inclusive:\n\nCreate a hashmap (freq) to store the frequency of cumulative sums.\nInitialize the cumulative sum sum as 0.\nInitialize cumuColSum to track the cumulative column sums for each row, starting from column i to column j.\nTraverse each row (k) from 0 to n-1:\n\nUpdate the cumuColSum[k] with the current value in matrix[k][j] plus the previous cumulative sum value.\nIncrement the frequency of the current cumulative sum sum in the freq map.\nUpdate sum by adding the current cumuColSum[k].\nAt each step in row traversal:\n\nIncrement the count by the frequency of (sum - target) in the freq map. This implies that there are freq[sum - target] submatrices that sum to the target value ending at the current row.\nThe count is the final result representing the total number of submatrices across all column pairs that sum up to the target value.\n\n\n\n# Complexity\n- Time complexity:O(m^2*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 numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {\n int n = matrix.size();\n int m = matrix[0].size();\n\n int count =0;\n\n for(int i=0;i<m;i++){\n vector<int> cumuColSum(n,0);\n\n for(int j=i;j<m;j++){\n unordered_map<int,int> freq;\n int sum = 0;\n for(int k=0;k<n;k++){\n cumuColSum[k] = matrix[k][j] + cumuColSum[k];\n freq[sum]++;\n sum += cumuColSum[k];\n count += freq[sum-target];\n \n }\n }\n }\n\n return count;\n }\n};\n```
2
0
['C++']
0
number-of-submatrices-that-sum-to-target
EASY JAVA SOLUTION || PREFIX SUM
easy-java-solution-prefix-sum-by-sauravm-5nu0
Intuition\n Describe your first thoughts on how to solve this problem. \n\n\n\n# Code\n\nclass Solution {\n public int numSubmatrixSumTarget(int[][] matrix,
Sauravmehta
NORMAL
2023-01-30T14:44:48.218383+00:00
2023-01-30T14:44:48.218419+00:00
550
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n\n# Code\n```\nclass Solution {\n public int numSubmatrixSumTarget(int[][] matrix, int target) {\n int result = 0;\n //Calculating prefix sum in all rows\n for(int i=0;i<matrix.length;i++){\n for(int j=1;j<matrix[0].length;j++){\n matrix[i][j] = matrix[i][j-1] + matrix[i][j]; \n }\n }\n\n //applying prefix Sum - HashMap technique\n for(int i=0;i<matrix.length;i++){\n int[] arr = new int[matrix[0].length+1];\n for(int j = i;j<matrix.length;j++){\n for(int k=0;k<matrix[0].length;k++){\n arr[k+1] = arr[k+1] + matrix[j][k];\n }\n result += targetSum(arr,target);\n }\n }\n return result;\n }\n\n // method for prefix sum - HashMap techinique\n private int targetSum(int[] arr,int k){\n int result = 0;\n Map<Integer,Integer> map = new HashMap<>();\n for(int i=0;i<arr.length;i++){\n if(map.containsKey(arr[i]-k))\n result += map.get(arr[i]-k);\n map.put(arr[i],map.getOrDefault(arr[i],0) + 1);\n }\n return result;\n }\n}\n```
2
0
['Java']
0
number-of-submatrices-that-sum-to-target
✅✅Faster || Easy To Understand || C++ Code
faster-easy-to-understand-c-code-by-__kr-1yos
Using Prefix && Hashmap\n\n Time Complexity :- O(N * N * M)\n\n Sapce Complexity :- O(N)\n\n\nclass Solution {\npublic:\n \n // this function is for findi
__KR_SHANU_IITG
NORMAL
2022-10-04T05:55:17.415007+00:00
2022-10-04T05:55:17.415066+00:00
486
false
* ***Using Prefix && Hashmap***\n\n* ***Time Complexity :- O(N * N * M)***\n\n* ***Sapce Complexity :- O(N)***\n\n```\nclass Solution {\npublic:\n \n // this function is for finding the no. of subarray which has sum equal to target\n \n int find(vector<int>& arr, int target)\n {\n int n = arr.size();\n \n int count = 0;\n \n unordered_map<int, int> mp;\n \n mp[0] = 1;\n \n int curr_sum = 0;\n \n for(int i = 0; i < n; i++)\n {\n curr_sum += arr[i];\n \n int need = curr_sum - target;\n \n if(mp.count(need))\n {\n count += mp[need];\n }\n \n mp[curr_sum]++;\n }\n \n return count;\n }\n \n \n int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {\n \n int n = matrix.size();\n \n int m = matrix[0].size();\n \n int count = 0;\n \n for(int i = 0; i < n; i++)\n {\n // arr will store the prefix sum between row [i, k]\n \n vector<int> arr(m, 0);\n \n for(int k = i; k < n; k++)\n {\n for(int j = 0; j < m; j++)\n {\n arr[j] += matrix[k][j];\n }\n \n // call find function\n \n count += find(arr, target);\n }\n }\n \n return count;\n }\n};\n```\n\n
2
0
['C', 'Prefix Sum', 'C++']
0
number-of-submatrices-that-sum-to-target
C++ modified Kadene's algorithm O(N*N*M + M)
c-modified-kadenes-algorithm-onnm-m-by-o-jcgw
\nclass Solution {\npublic:\n \n //number of subarrays having sum equals to k\n int go(vector<int> &nums, int k)\n {\n unordered_map<int,int>
osmanay
NORMAL
2022-07-18T18:47:21.029224+00:00
2022-07-18T18:47:39.125137+00:00
189
false
```\nclass Solution {\npublic:\n \n //number of subarrays having sum equals to k\n int go(vector<int> &nums, int k)\n {\n unordered_map<int,int> m;\n \n int sum=0,ans=0;\n \n m[0] = 1;\n \n for(int num:nums)\n {\n sum += num;\n int target = sum - k;\n if(m.count(target))\n ans += m[target];\n \n m[sum]++;\n }\n return ans;\n } \n //----------------------------------------------------------------\n int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {\n \n int n = matrix.size(), m = matrix[0].size();\n \n int res = 0;\n \n for(int i=0; i<n; i++)\n {\n vector<int> temp(m,0); \n for(int j=i; j<n; j++)\n {\n for(int k=0; k<m; k++)\n temp[k] += matrix[j][k];\n \n //all sub-matrices between row i and j.\n res += go(temp, target);\n } \n }\n return res; \n }\n};\n```
2
0
['Dynamic Programming']
0
number-of-submatrices-that-sum-to-target
Similar to "Subarray with target k"
similar-to-subarray-with-target-k-by-raj-aqqr
\nclass Solution {\npublic:\n int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {\n \n int ro=matrix.size(),co=matrix[0].size(
rajat241302
NORMAL
2022-07-18T18:15:23.651407+00:00
2022-07-18T18:15:50.600790+00:00
71
false
```\nclass Solution {\npublic:\n int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {\n \n int ro=matrix.size(),co=matrix[0].size();\n \n if(ro<1)\n return 0;\n //prefix sum \n for(int r=0;r<ro;r++)\n for(int c=1;c<co;c++)\n matrix[r][c]+=matrix[r][c-1];\n \n int count=0;\n for(int c1=0;c1<co;c1++)\n for(int c2=c1;c2<co;c2++)\n {\n //appling "subarray with sum k" between the c1 and c2 || no of element is no of rows \n unordered_map<int,int>mp;\n int sum=0;\n mp[0]=1;\n for(int r=0;r<ro;r++)\n {\n sum+=matrix[r][c2]-(c1>0?matrix[r][c1-1]:0);// sum of row between c1 and c2;\n int find=sum-target; \n if(mp.find(find)!=mp.end())\n count+=mp[find];\n mp[sum]++;\n }\n }\n return count++;\n \n \n }\n};\n```
2
0
['Matrix', 'Prefix Sum']
0
number-of-submatrices-that-sum-to-target
✅ C++ , Variation of Subarray sum equals k
c-variation-of-subarray-sum-equals-k-by-ueojy
\nclass Solution {\npublic:\n int numSubmatrixSumTarget(vector<vector<int>>& mat, int target) {\n int n=mat.size();\n int m=mat[0].size();\n
H4saki_96
NORMAL
2022-07-18T17:15:35.588076+00:00
2022-07-18T17:15:35.588117+00:00
109
false
```\nclass Solution {\npublic:\n int numSubmatrixSumTarget(vector<vector<int>>& mat, int target) {\n int n=mat.size();\n int m=mat[0].size();\n \n // STEP 01 : prefix sum\n for(int i=0;i<n;i++){\n for(int j=1;j<m;j++){\n mat[i][j] += mat[i][j-1];\n }\n }\n \n int res=0;\n \n // STEP 02 : for every pair of column perform operation - subarray sum technique with \n // with sliding window to get every apir of column\n for(int c1=0;c1<m;c1++){\n for(int c2=c1;c2<m;c2++){\n \n // since we handled every column pair now work on operation on every rows\n // subarray sum equals k technique\n int sum=0;\n unordered_map<int,int> mp;\n mp[0]=1;\n \n for(int row=0;row<n;row++){\n \n sum+=mat[row][c2];\n \n // remove extra left part(search space) if there \n if(c1>0) sum-=mat[row][c1-1];\n \n // exact same as subarray sum equals k\n int srch = sum-target;\n \n if(mp.find(srch)!=mp.end()) res += mp[srch];\n \n mp[sum]++;\n }\n }\n }\n return res;\n }\n};\n```
2
0
['Array', 'Hash Table', 'C', 'Sliding Window', 'Prefix Sum']
0
number-of-submatrices-that-sum-to-target
Prefix Sum Easy C++
prefix-sum-easy-c-by-you_r_mine-27cv
\nclass Solution {\npublic:\n int numSubmatrixSumTarget(vector<vector<int>>& A, int target) {\n int res = 0, m = A.size(), n = A[0].size();\n fo
you_r_mine
NORMAL
2022-07-18T14:30:25.970310+00:00
2022-07-18T14:30:25.970349+00:00
126
false
```\nclass Solution {\npublic:\n int numSubmatrixSumTarget(vector<vector<int>>& A, int target) {\n int res = 0, m = A.size(), n = A[0].size();\n for (int i = 0; i < m; i++)\n for (int j = 1; j < n; j++)\n A[i][j] += A[i][j - 1]; // prefix sum of matrix row wise \n\n unordered_map<int, int> counter;\n for (int i = 0; i < n; i++) {\n for (int j = i; j < n; j++) {\n counter = {{0,1}};\n int cur = 0;\n for (int k = 0; k < m; k++) {\n cur += A[k][j] - (i > 0 ? A[k][i - 1] : 0);\n res += counter.find(cur - target) != counter.end() ? counter[cur - target] : 0; \n counter[cur]++;\n }\n }\n }\n return res;\n }\n};\n```
2
0
[]
0
number-of-submatrices-that-sum-to-target
Python | Using Range Sum Query 2D O(M^2N) | M<N | Faster | 99%
python-using-range-sum-query-2d-om2n-mn-spqpw
Similar to LC 304: Range Sum Query 2D| Approach 4, create a 2D cache : dp such that dp(row,col) is the sum of the subarray (0,0) to (row,col)\n\nNow, applying
dpsingh_287
NORMAL
2022-07-18T14:09:29.823777+00:00
2022-07-18T14:09:29.823823+00:00
255
false
Similar to [LC 304: Range Sum Query 2D| Approach 4](https://leetcode.com/problems/range-sum-query-2d-immutable/), create a 2D cache : dp such that dp(row,col) is the sum of the subarray (0,0) to (row,col)\n\nNow, applying logic similar to [LC 560: Subarray sum equals k](https://leetcode.com/problems/subarray-sum-equals-k/) we need to create a hashmap but since this is in 2D, we fix the row limits row1 and row2. Then iterate through the columns calculating the presum of the subarray up till that column for the fixed (row1, row2), simultaneuously increasing the hashmap value by 1.\nFor a given presum, if presum-target exists in the hash, we increase the ans count by the value of hash[presum-target]\n\nNote: We don\'t increment the presum variable and instead assign it directly since our 2d dp already accounts for the prefix sum up until that point! \n\n```\nclass Solution:\n def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:\n \n if len(matrix)>len(matrix[0]):\n new=[[0]*len(matrix) for i in range(len(matrix[0]))]\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n new[j][i]=matrix[i][j]\n return self.numSubmatrixSumTarget(new,target)\n\n\n self.dp=[[0]*(len(matrix[0])+1)for i in range(len(matrix)+1)]\n for i in range(1,len(matrix)+1):\n for j in range(1,len(matrix[0])+1):\n self.dp[i][j]=self.dp[i][j-1]+self.dp[i-1][j]-self.dp[i-1][j-1]+matrix[i-1][j-1]\n \n ans=0\n for row1 in range(len(matrix)):\n for row2 in range(row1,len(matrix)):\n pres=0\n myhash={0:1}\n for col1 in range(len(matrix[0])):\n presum=self.dp[row2+1][col1+1]-self.dp[row1][col1+1]\n if presum-target in myhash:\n ans+=myhash[pres-target]\n myhash[pres]=myhash.get(pres,0)+1\n \n return(ans)\n \n```
2
0
['Dynamic Programming', 'Python']
0
number-of-submatrices-that-sum-to-target
Least Runtime Solution
least-runtime-solution-by-day_tripper-ffk7
\nclass Solution:\n def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:\n n, m = len(matrix), len(matrix[0])\n answer
Day_Tripper
NORMAL
2022-07-18T09:09:12.917671+00:00
2022-07-18T09:09:12.917716+00:00
23
false
```\nclass Solution:\n def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:\n n, m = len(matrix), len(matrix[0])\n answer = 0\n \n for i in range(n):\n for j in range(1, m):\n matrix[i][j] += matrix[i][j - 1]\n \n for j in range(m):\n for k in range(j, m):\n d, c = {0: 1}, 0\n for i in range(n):\n c += matrix[i][k] - (matrix[i][j - 1] if j else 0)\n if c - target in d:\n answer += d[c - target]\n d[c] = d[c] + 1 if c in d else 1 \n return answer\n```
2
0
['Matrix']
0
minimum-average-difference
Prefix Sum | O(1) Space
prefix-sum-o1-space-by-kamisamaaaa-i8ep
C++:\n\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\n \n int n(size(nums)), minAverageDifference(INT_MAX), in
kamisamaaaa
NORMAL
2022-04-30T16:01:17.253653+00:00
2022-12-04T05:54:35.761890+00:00
8,517
false
# C++:\n```\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\n \n int n(size(nums)), minAverageDifference(INT_MAX), index;\n \n long long sumFromFront(0), sumFromEnd(0);\n for (auto& num : nums) sumFromEnd += num;\n \n for (int i=0; i<n; i++) {\n sumFromFront += nums[i];\n sumFromEnd -= nums[i];\n int a = sumFromFront / (i+1); // average of the first i + 1 elements.\n int b = (i == n-1) ? 0 : sumFromEnd / (n-i-1); // average of the last n - i - 1 elements.\n \n if (abs(a-b) < minAverageDifference) {\n minAverageDifference = abs(a-b);\n index = i;\n }\n }\n return index;\n }\n};\n```\n\n# Python:\n```\n\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n\n sumEnd, sumFront, res, diff, n = 0, 0, 0, 1e9, len(nums)\n for num in nums:\n sumEnd += num\n\n for i in range(n):\n sumFront += nums[i]\n sumEnd -= nums[i]\n\n avg1 = sumEnd//(n-1-i) if i != n-1 else 0\n avg2 = sumFront//(i+1)\n\n if abs(avg1-avg2) < diff:\n diff = abs(avg1-avg2)\n res = i\n \n return res\n```
94
0
['C++', 'Python3']
13
minimum-average-difference
✅ C++ || EASY || DETAILED EXPLAINATION || O(N)
c-easy-detailed-explaination-on-by-ayush-jc19
PLEASE UPVOTE IF YOU FIND MY APPROACH HELPFUL, MEANS A LOT \uD83D\uDE0A\n\nIntuition: We just have to take average difference and return the index giving minimu
ayushsenapati123
NORMAL
2022-12-04T02:59:24.439871+00:00
2022-12-04T02:59:24.439899+00:00
3,701
false
**PLEASE UPVOTE IF YOU FIND MY APPROACH HELPFUL, MEANS A LOT \uD83D\uDE0A**\n\n**Intuition:** We just have to take average difference and return the index giving minimum average difference.\n\n**Approach:**\n* Take out `totalsum` which will be sum of all n elements and `currentsum` which will be the sum till `ith` index.\n* Calculate the `avg1` till ith index and `avg2` till n-1-ith index.\n* Now take absolute diff btw `avg1` and `avg2` and keep tracking the index giving minimum diff.\n* return the index giving minimum diff.\n\n```\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\n long totalsum = 0, currentsum = 0;\n int n = nums.size();\n \n // calc totalsum\n for(auto i : nums)\n totalsum += i;\n \n int mini = INT_MAX;\n int indexans = 0;\n \n // calc the avg1 till ith index and avg2 till n-1-ith index\n // now take absolute diff btw avg1 and avg2 and keep tracking the index giving minimum diff\n // return the index giving minimum diff\n for(int i=0; i<n; i++)\n {\n currentsum += nums[i];\n int avg1 = currentsum/(i+1);\n if(i==n-1)\n {\n if(avg1<mini)\n return n-1;\n else\n break;\n }\n int avg2 = (totalsum - currentsum)/(n-i-1);\n \n if(abs(avg1-avg2)<mini)\n {\n mini = abs(avg1-avg2);\n indexans = i;\n }\n }\n \n return indexans;\n }\n};\n```\n**Time Complexity** => `O(N)`\n**Space Complexity** => `O(1)`\n\n![image](https://assets.leetcode.com/users/images/f676b124-08ca-4c1c-adc9-0cc3bf101cee_1670122663.4309115.png)\n
69
13
['C++']
9
minimum-average-difference
A few lines Java Solution
a-few-lines-java-solution-by-steve12138-lj9a
Calculate the sum first and then minus the left sum in te for loop.\n\npublic int minimumAverageDifference(int[] nums) {\n\tint len = nums.length, res = 0;\n\tl
steve12138
NORMAL
2022-04-30T16:04:11.666481+00:00
2022-04-30T16:08:55.761838+00:00
3,632
false
Calculate the sum first and then minus the left sum in te for loop.\n```\npublic int minimumAverageDifference(int[] nums) {\n\tint len = nums.length, res = 0;\n\tlong min = Integer.MAX_VALUE, sum = 0, leftSum = 0, rightSum = 0;\n\tfor (int num : nums)\n\t\tsum += num;\n\tfor (int i = 0; i < len; i++) {\n\t\tleftSum += nums[i];\n\t\trightSum = sum - leftSum;\n\t\tlong diff = Math.abs(leftSum / (i + 1) - (len - i == 1 ? 0 : rightSum / (len -i - 1)));\n\t\tif (diff < min) {\n\t\t\tmin = diff;\n\t\t\tres = i;\n\t\t}\n\t}\n\treturn res;\n}\n```
44
1
['Prefix Sum', 'Java']
6
minimum-average-difference
🔥Python3🔥 Prefix sum
python3-prefix-sum-by-meidachen-d6s5
Algorithm\n(1) To get the average of something, we first need to get the sum.\n(2) At each index i, if we know the sum of the first i + 1 elements, and the sum
MeidaChen
NORMAL
2022-12-04T02:07:27.641586+00:00
2024-01-04T19:23:01.720253+00:00
1,876
false
**Algorithm**\n(1) To get the average of something, we first need to get the sum.\n(2) At each index ```i```, if we know the sum of the first i + 1 elements, and the sum of the last n - i - 1 elements, we can calculate their averages.\n - We can compute the sum of the first i + 1 elements by adding the value at ```i``` to the sum of the first ```i``` elements (prefix sum).\n - We can get the sum of the last n - i - 1 elements by using the total sum of the entire array - the sum of the first i + 1 elements\n\n(3) At each ```i```, we just need to store ```i``` if the current ```absolute difference``` is less than any ```absolute difference``` we have seen before.\n**TC: O(n)**\n\n```python\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n # leftSum represents the sum of the first i + 1 elements at index i\n n, totalSum, leftSum = len(nums), sum(nums), 0\n \n # res[0] is the minimum absolute difference, and res[1] is the index.\n res = [inf,inf]\n \n for i,v in enumerate(nums):\n leftSum += v\n \n leftAvg = leftSum//(i+1)\n # when we are at the last index, the right hand side sum is 0. (To aviod divide by zero error)\n rightAvg = (totalSum-leftSum)//(n-i-1) if n-i-1!=0 else 0\n absDif = abs(leftAvg-rightAvg)\n \n # min will take care of "If there are multiple such indices, return the smallest one."\n res = min(res,[absDif,i])\n \n # return the index\n return res[1]\n```\n\n**Upvote** if you like this post.\n\n**Connect with me on [LinkedIn](https://www.linkedin.com/in/meida-chen-938a265b/)** if you\'d like to discuss other related topics\n\n\uD83C\uDF1F If you are interested in **Machine Learning** || **Deep Learning** || **Computer Vision** || **Computer Graphics** related projects and topics, check out my **[YouTube Channel](https://www.youtube.com/@meidachen8489)**! Subscribe for regular updates and be part of our growing community.
32
1
[]
3
minimum-average-difference
Python 3 || 8 lines, w/ explanation and example || T/S: 95% / 80%
python-3-8-lines-w-explanation-and-examp-pbqi
\nclass Solution:\n def minimumAverageDifference(self, nums: list[int]) -> int:\n\n # Example: nums =
Spaulding_
NORMAL
2022-12-04T04:34:57.077478+00:00
2024-06-13T03:33:44.410223+00:00
984
false
```\nclass Solution:\n def minimumAverageDifference(self, nums: list[int]) -> int:\n\n # Example: nums = [2, 5, 4, 3, 1, 9, 5, 3]\n n = len(nums) # \n pref = list(accumulate(nums)) # pref = [2, 7,11,14,15,24,29,32]\n # i: 0 1 2 3 4 5 6 7\n # \n ans = (pref[-1]//n, n-1) # ans = (32//8,8-1) = (4,7)\n \n for i in range(n-1): # i 1st ave 2nd ave abs diff ans\n diff = abs(pref[i]//(i+1) - # \u2013\u2013\u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\n (pref[-1] - pref[i])//(n-i-1)) # (4, 7)\n\n # 0 2//1 = 2 29//7 = 4 2 (2, 0)\n ans = min(ans, (diff,i)) # 1 7//2 = 3 25//6 = 4 1 (1, 1)\n # 2 11//3 = 3 21//5 = 4 1 (1, 1)\n return ans[1] # 3 14//4 = 3 18//4 = 4 1 (1, 1)\n # 4 15//5 = 3 17//3 = 5 2 (1, 1)\n # 5 24//6 = 4 8//2 = 4 0 (0, 5)\n # 6 29//7 = 4 3//1 = 3 1 (0, 5)\n # |\n # return ans[1]\n```\n[https://leetcode.com/submissions/detail/854132107/](https://leetcode.com/submissions/detail/854132107/)\n\nI could be wrong, but I think that time is *O*(*N*) and space is *O*(*N*), in which *N* ~ `len(nums)`.
24
0
['Python']
4
minimum-average-difference
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
leetcode-the-hard-way-explained-line-by-ynucm
\uD83D\uDD34 Check out LeetCode The Hard Way for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our Discord for live discussion.\n\uD83D\uDF
__wkw__
NORMAL
2022-12-04T03:07:42.232102+00:00
2022-12-04T03:07:42.232140+00:00
1,183
false
\uD83D\uDD34 Check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our [Discord](https://discord.gg/Nqm4jJcyBf) for live discussion.\n\uD83D\uDFE2 Give a star on [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post if you like it.\n\n---\n\n```cpp\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\n int ans = 0, n = nums.size(), mi = INT_MAX;\n // since we need the sum for first i + 1 and last n - i - 1 elements\n // we can pre-calculate it first\n // it is called prefix sum and suffix sum\n vector<long long> pref(n);\n // prev[0] is the first element\n pref[0] = nums[0];\n // starting from i = 1, pref[i] is the sum + the current element\n for (int i = 1; i < n; i++) pref[i] = pref[i - 1] + nums[i];\n // then we can iterate each number\n for (int i = 0; i < n; i++) {\n // now we know the prefix sum\n // the suffix sum is simply pref[n - 1] - pref[i]\n long long k = abs((pref[i] / (i + 1)) - ((pref[n - 1] - pref[i]) / max(n - i - 1, 1)));\n // check the min and update ans\n if (k < mi) {\n mi = k;\n ans = i;\n }\n }\n return ans;\n }\n};\n```
22
0
['C', 'Prefix Sum', 'C++']
1
minimum-average-difference
Simple O(n) time O(1) Space beginner friendly.
simple-on-time-o1-space-beginner-friendl-6n3z
Intuition\nwe have to take count of left and right sum at each index.\n\n# Approach\nwe will be taking left sum and right sum.\nwe will find the average at each
madhavdua108
NORMAL
2022-12-04T06:47:12.480999+00:00
2022-12-04T06:47:12.481045+00:00
1,077
false
# Intuition\nwe have to take count of left and right sum at each index.\n\n# Approach\nwe will be taking left sum and right sum.\nwe will find the average at each index.\nIf the current difference is less than last minimum difference than update last minimum difference and ans index.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n int n=nums.length;\n //if length==1 difference=0\n if(n==1)return 0;\n // initialsing left and right sum\n long right=0,left=0;\n //ans will contain index\n int ans=0;\n //mina will contain minimum difference found till now\n long mina=100001;\n for(Integer i:nums){right+=i;}//right=total sum\n\n //iterating on array and obtaining corresponding difference\n for(int i=0; i<n; i++){\n\n //left sum increases on each iteration\n left+=nums[i];\n //right sum decreases on each iteration\n right-=nums[i];\n //avl -> average of left side\n long avl=left/(i+1);\n //avr-> average of right side\n long avr=0;\n //for last index right=0 , avr=0\n if(i!=n-1){avr=right/(n-1-i);}\n\n //if current difference is less than mina \n if(Math.abs(avl-avr)<mina)\n {\n //update mina \n mina=Math.abs(avl-avr);\n //update ans index\n ans=i;}\n }\n // return ans index\n return ans;\n }\n}\n//Thank you\n//Upvote if found helpful.\n```
18
0
['Java']
2
minimum-average-difference
✅ [Python/C++] running prefix & suffix (explained)
pythonc-running-prefix-suffix-explained-dedwx
\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.\n*\nThis solution employs computing running prefix and suffix of the input array. Time complexity is linear: *O
stanislav-iablokov
NORMAL
2022-12-04T00:55:00.812831+00:00
2022-12-04T02:09:02.139438+00:00
1,600
false
**\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n****\nThis solution employs computing running prefix and suffix of the input array. Time complexity is linear: **O(N)**. Space complexity is constant: **O(1)**.\n****\n\n**Python #1.** First, linear-space solution with precomputed prefix & suffix.\n```\nimport numpy as np\n\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n \n first, last = [], [0]\n f = l = 0\n \n for i,n in enumerate(nums,start=1):\n first.append((f:=f+n) // i)\n\n for i,n in enumerate(reversed(nums[1:]),start=1):\n last.append((l:=l+n) // i)\n \n last.reverse()\n \n diff = [abs(f-l) for f,l in zip(first,last)]\n \n return np.argmin(diff)\n```\n\n**Python #2.** Constant-space solution with running prefix & suffix.\n```\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n \n i, m = 0, inf # running prefix starts from 0\n pfx, sfx = 0, sum(nums) # running suffix starts from sum of array\n \n for j,n in enumerate(nums,start=1):\n pfx, sfx = pfx+n, sfx-n # update prefix (+) and suffix (-)\n k = len(nums)-j or 1 # prevent suffix length to be 0\n d = abs(pfx//j - sfx//k)\n if d < m:\n m, i = d, j-1\n\n return i\n```\n\n**C++.** Constant-space solution with running prefix & suffix.\n```\nclass Solution \n{\npublic:\n int minimumAverageDifference(vector<int>& nums) \n {\n long i = 0, j = 0, m = LONG_MAX, k, d;\n long pfx = 0, sfx = accumulate(nums.begin(), nums.end(), 0L);\n \n for (int n : nums)\n {\n pfx += n, sfx -= n, j += 1;\n k = nums.size() - j;\n d = abs(pfx/j - sfx/(k?k:1));\n if (d < m) m = d, i = j - 1;\n }\n \n return i;\n }\n};\n```
15
0
[]
4
minimum-average-difference
C++ || Easy to understand O(N) solution
c-easy-to-understand-on-solution-by-yash-q6g6
\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) \n {\n int n=nums.size();\n \n long long right_sum = 0;
Yash2arma
NORMAL
2022-04-30T16:27:40.639794+00:00
2022-04-30T16:27:40.639825+00:00
1,300
false
```\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) \n {\n int n=nums.size();\n \n long long right_sum = 0;\n for(auto it:nums) right_sum += it;\n \n int mini = INT_MAX;\n int idx = 0;\n \n long long left_sum = 0;\n \n for(int i=0; i<n; i++)\n {\n left_sum += nums[i];\n right_sum -= nums[i];\n \n long long first = (left_sum/(i+1));\n \n long long last = i<n-1 ? (right_sum/(n-i-1)) : 0;\n \n int diff = abs(first - last);\n \n if(diff < mini)\n {\n mini = diff;\n idx = i;\n }\n }\n \n return idx;\n }\n};\n```
13
1
['C', 'C++']
1
minimum-average-difference
✅✅ C++ || Easy Solution ||
c-easy-solution-by-himanshu_52-ygq4
Step by Step Approach---\n1-Calculate prefix sum for every index and store it in array.\n2-for every index calculate average difference and store its minimum va
himanshu_52
NORMAL
2022-04-30T16:40:04.535331+00:00
2022-04-30T17:34:42.923613+00:00
1,744
false
**Step by Step Approach---\n1-Calculate prefix sum for every index and store it in array.\n2-for every index calculate average difference and store its minimum value index.\n***\n**Code**\n\'\'\'\n\nclass Solution {\npublic:\n\n int minimumAverageDifference(vector<int>& nums) {\n int n=nums.size();\n if(n==1) return 0;\n long long pre[n]; //to store prefix sum\n pre[0]=nums[0];\n\t\t\n\t\t//calculating prefix sum\n for(int i=1;i<n;i++) pre[i]=pre[i-1]+nums[i];\n\t\t\n long long res=INT_MAX;\n int ind=0;\n\t\t\n\t\t// calculating minimum average for i=0 to i=n-2\n for(int i=1;i<n;i++) {\n int k=(abs(pre[i-1]/i-(pre[n-1]-pre[i-1])/(n-i)));\n if(res>k){\n res=k;\n ind=i-1;\n }\n }\n\t\t\n\t\t//special case for i=n-1\n if(res>abs(pre[n-1]/n)){\n res=abs(pre[n-1]/n);\n ind=n-1;\n }\n return ind;\n }\n};\n\'\'\'
12
0
['Math', 'C', 'Prefix Sum']
4
minimum-average-difference
[Java] Runtime: 17ms, faster than 96.63% || Prefix sum || Time O(n) || Space O(1)
java-runtime-17ms-faster-than-9663-prefi-6ke6
\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n long min = Integer.MAX_VALUE, sum = 0;\n for (int i : nums) sum += i;\
decentos
NORMAL
2022-12-04T02:51:34.599508+00:00
2022-12-04T02:52:54.368493+00:00
1,435
false
```\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n long min = Integer.MAX_VALUE, sum = 0;\n for (int i : nums) sum += i;\n int leftIndex = 0, resultIndex = -1;\n long prefixSum = 0;\n\n while (leftIndex < nums.length) {\n prefixSum += nums[leftIndex];\n long leftAverage = prefixSum / (leftIndex + 1);\n long sumRight = sum - prefixSum;\n if (sumRight != 0) sumRight /= nums.length - leftIndex - 1;\n long res = Math.abs(leftAverage - sumRight);\n if (res < min) {\n min = res;\n resultIndex = leftIndex;\n }\n leftIndex++;\n }\n return resultIndex;\n }\n}\n```\n\n![image](https://assets.leetcode.com/users/images/5d0ba1a4-fea0-4734-bc00-cdf00e45d5b4_1670122282.0697427.png)\n
9
1
['Java']
2
minimum-average-difference
Python very easy detailed code. Use one queue to track moving elements (with image)
python-very-easy-detailed-code-use-one-q-aa67
Idea is to use a queue to have left_sum and right_sum.\nAnd use a queue to track elements moving from right_sum to left_sum. Also update the length which is the
vineeth_moturu
NORMAL
2022-04-30T16:10:54.088716+00:00
2022-05-01T04:26:30.455448+00:00
1,164
false
Idea is to use a queue to have left_sum and right_sum.\nAnd use a queue to track elements moving from right_sum to left_sum. Also update the length which is the divisor.\n\n**Note**: This can also be done without a queue and make space complexity to O(1). But using a queue makes it alot easier to write and understand. Time complexity remains the same.\n\nOnce an element is removed from left of the queue (which contains right part of array). \n1. Add it to left_sum\n2. Remove it from right_sum\n3. Add 1 to left_length\n4. Remove 1 from right_length\n\n![image](https://assets.leetcode.com/users/images/567bc13c-a84e-4c00-a455-0037ed13124b_1651341859.6866913.png)\n\n\n\n```\ndef minimumAverageDifference(self, nums: List[int]) -> int:\n n = len(nums)\n if n == 1:\n return 0\n\n queue = deque(nums[1: ])\n\n left_sum = sum(nums[0: 1])\n right_sum = sum(queue)\n\n left_length = 1\n right_length = n - 1\n\n i = 0\n\n min_avg = sys.maxsize\n min_avg_idx = None\n\n while i < n:\n left_avg = left_sum // left_length\n if right_length:\n right_avg = right_sum // right_length\n else:\n right_avg = 0\n\n diff = abs(left_avg - right_avg)\n if diff < min_avg:\n min_avg = diff\n min_avg_idx = i\n\n # if queue is empty, we can stop. as it is the end.\n if not queue:\n break\n\t\t# remove ele from left of the queue\n element = queue.popleft()\n\n\t\t# update for next iteration\n left_sum = left_sum + element\n right_sum = right_sum - element\n\n left_length += 1\n right_length -= 1\n\n i += 1\n\n return min_avg_idx\n```
9
1
['Python']
3
minimum-average-difference
✅C++ || ✅Prefix Sum || ✅Commented Solution || ✅Easy
c-prefix-sum-commented-solution-easy-by-utf9a
\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) \n {\n int n = nums.size();\n long long total = 0;\n lo
mayanksamadhiya12345
NORMAL
2022-12-04T05:40:54.812693+00:00
2022-12-04T05:40:54.812730+00:00
338
false
```\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) \n {\n int n = nums.size();\n long long total = 0;\n long long curr = 0;\n for(auto it : nums) total += it;\n \n long long res;\n long long temp = INT_MAX;\n \n for(int i=0;i<n;i++)\n {\n curr += nums[i]; // curr left sum\n long long avg1 = curr/(i+1); // left part avg\n \n // if we are on last idx then just check for left part\n if(i==n-1)\n {\n if(avg1 < temp) \n return n-1;\n else \n break;\n }\n \n long long avg2 = (total-curr)/(n-i-1); // right part avg\n \n // if we got a new min val then update index\n if(abs(avg1-avg2) < temp)\n {\n temp = abs(avg1-avg2);\n res = i;\n }\n }\n \n return res;\n }\n};\n```
8
0
['C', 'Prefix Sum']
0
minimum-average-difference
C++ || Easy to understand || No Extra Space
c-easy-to-understand-no-extra-space-by-m-8jqo
\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) \n {\n int n = nums.size();\n long long totalSum = 0;\n
mohakharjani
NORMAL
2022-12-04T04:42:42.436930+00:00
2022-12-04T05:31:40.798173+00:00
1,173
false
```\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) \n {\n int n = nums.size();\n long long totalSum = 0;\n for (int num : nums) totalSum += num;\n //=======================================================================\n int mnAvgDiff = INT_MAX, mnAvgDiffIdx = -1;\n long long preSum = 0;\n for (int i = 0; i < n; i++)\n {\n preSum += nums[i];\n long long postSum = totalSum - preSum;\n //==================================================\n int preCount = i + 1;\n int postCount = n - preCount;\n int preAvg = preSum / preCount;\n int postAvg = (postCount == 0)? 0 : (postSum / postCount);\n //====================================================\n int avgDiff = abs(preAvg - postAvg);\n if (avgDiff < mnAvgDiff)\n {\n mnAvgDiff = avgDiff;\n mnAvgDiffIdx = i;\n }\n }\n //=======================================================================\n return mnAvgDiffIdx;\n }\n};\n```
8
0
['C', 'C++']
1
minimum-average-difference
python beats 99.8%, easy to understand
python-beats-998-easy-to-understand-by-u-cofj
Code\n\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n sumleft, sumright, lengthright, lengthleft, min, ind, = 0, sum
ulyanovmmm
NORMAL
2022-12-04T16:44:58.340623+00:00
2022-12-05T09:43:42.903562+00:00
365
false
# Code\n```\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n sumleft, sumright, lengthright, lengthleft, min, ind, = 0, sum(nums), len(nums), 0, 9999999, 0\n for i in range(len(nums)):\n sumleft += nums[i]\n sumright -= nums[i]\n lengthleft+=1\n lengthright-=1\n if lengthright!=0:\n val = (abs(sumleft//lengthleft - sumright//lengthright))\n else:\n val = (abs(sumleft//lengthleft))\n if val<min:\n min=val\n ind = i\n return ind\n```
7
0
['Python', 'Python3']
2
minimum-average-difference
✅ [Java] Easy Java Solution using Arrays, running prefix & suffix (explained).
java-easy-java-solution-using-arrays-run-4y3w
This question can be easily solved if you know the basic operations of Arrays in java.\n Although it\'s not the best optimised code but it can be easily underst
devesh096
NORMAL
2022-12-04T07:04:36.126175+00:00
2022-12-04T16:32:23.720154+00:00
946
false
## This question can be easily solved if you know the basic operations of Arrays in java.\n Although it\'s not the best optimised code but it can be easily understood by the beginners.\n\nFirst we are calculating the total sum of the elements of array nums and storing it in the variable sum.\n\nand then we are calculating leftsum,rightsum and Average Difference for every Index and we are storing the index of minimum average index in the variable index.\nand finally we are returning the index.\n**Runtime: 17 ms, faster than 95.63%**\n```\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n int l = nums.length; \n int index = 0;\n long min = Integer.MAX_VALUE, sum = 0, leftsum = 0, rightsum = 0;\n for (int j = 0; j < l; j++) {\n sum = sum + nums[j];\n }\n for (int i = 0; i < l; i++) {\n leftsum += nums[i];\n rightsum = sum - leftsum;\n long diff = Math.abs(leftsum / (i + 1) - (l - i == 1 ? 0 : rightsum / (l - i - 1))); // if number of rightsum values = 0\n if (diff < min) {\n min = diff;\n index = i;\n }\n }\n return index;\n\n }\n}\n```\n# **\n# Please upvote if this helps**\n## Thanks
7
0
['Array', 'Java']
2
minimum-average-difference
It works, but looks clumsy
it-works-but-looks-clumsy-by-anikit-7wo2
Three ideas that I tried to implement here:\n1. Avoid casting\n2. Avoid inside-loop guard clauses, i.e. checks for edge cases like division by zero\n3. Return e
anikit
NORMAL
2022-12-04T11:19:25.308805+00:00
2023-01-03T21:31:28.657755+00:00
223
false
Three ideas that I tried to implement here:\n1. Avoid casting\n2. Avoid inside-loop guard clauses, i.e. checks for edge cases like division by zero\n3. Return early if the array is all zeroes\n\nTo 1: The only casting is done when summing up the array. Seems unavoidable.\nTo 2: Check the last index when returning (not inside the for loop).\n```csharp\npublic class Solution\n{\n public int MinimumAverageDifference(int[] nums)\n {\n long sum = nums.Sum(n => (long)n);\n if (sum == 0) return 0;\n\n int minIndex = 0;\n int len = nums.Length;\n long front = 0;\n long minDiff = long.MaxValue;\n\n for (int i = 1; i < len; i++)\n {\n front += nums[i - 1];\n long diff = Math.Abs((sum - front) / (len - i) - front / i);\n if (diff < minDiff) (minDiff, minIndex) = (diff, i - 1);\n }\n\n return sum / len < minDiff ? len - 1 : minIndex;\n }\n}\n```
5
0
['C#']
0
minimum-average-difference
Javascript O(n) solution
javascript-on-solution-by-lm49-cjom
Intuition\n Describe your first thoughts on how to solve this problem. \nFor each calculation by index, we can separate nums into two sub-arrays: left-side and
lm49
NORMAL
2022-12-04T00:48:46.783990+00:00
2022-12-04T00:48:46.784027+00:00
547
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor each calculation by index, we can separate `nums` into two sub-arrays: left-side and right-side. Making the sum of entire left and right sides is not needed, just substract from right and add to left.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse two variables to save the sum of each side. At first, left side sum is 0 and right side sum is sum(nums). On each iteration i, add nums[i] to the left and substract nums[i] to the right, then calculate absolute average and update answer.\n\n# Complexity\n- Time complexity: O(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```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar minimumAverageDifference = function(nums) {\n let nL=nums.length;\n let leftSum = 0;\n let rightSum = nums.reduce((p,n)=>{return p+n},0);\n\n let minimum = Infinity;\n let ans = Infinity;\n for (let i=0; i<nL; i++){\n leftSum += nums[i];\n rightSum -= nums[i];\n let res = Math.abs(Math.floor(((leftSum)/(i+1))) - Math.floor(((rightSum)/Math.max(1,(nL-1-i)))));\n if(res < minimum){\n minimum = res;\n ans = i;\n }\n }\n return ans;\n};\n```
5
0
['JavaScript']
3
minimum-average-difference
✔️PYTHON || EASY || ✔️ BEGINER FRIENDLY
python-easy-beginer-friendly-by-karan_80-7x7l
l -> sum of left array\nr -> sum of right array\n\nAs we keep iterating we keep adding to l and delete from r\n\n\n\nclass Solution:\n def minimumAverageDiff
karan_8082
NORMAL
2022-06-01T13:39:44.261824+00:00
2022-06-01T13:39:44.261848+00:00
454
false
l -> sum of left array\nr -> sum of right array\n\nAs we keep iterating we keep adding to **l** and delete from **r**\n![image](https://assets.leetcode.com/users/images/77ee6f46-f8ed-40a1-80d0-8cc4dff1d386_1654090771.8141484.jpeg)\n\n```\nclass Solution:\n def minimumAverageDifference(self, a: List[int]) -> int:\n l=0\n r=sum(a)\n z=100001\n y=0\n n=len(a)\n \n for i in range(n-1):\n l+=a[i]\n r-=a[i]\n \n d=abs((l//(i+1))-(r//(n-i-1)))\n if d<z:\n z=d\n y=i\n \n if sum(a)//n<z:\n y=n-1\n \n return y\n```\n![image](https://assets.leetcode.com/users/images/ef6ef7cc-c4b8-48f3-ab7a-eb7fe4296e67_1654090737.6638153.jpeg)\n
5
0
['Python', 'Python3']
1
minimum-average-difference
Prefix Sum
prefix-sum-by-votrubac-n0q3
We handle the average of zero elements in the very end. \n\nC++\ncpp\nint minimumAverageDifference(vector<int>& nums) {\n vector<long long> ps{0};\n for (
votrubac
NORMAL
2022-05-01T22:37:27.429844+00:00
2022-05-03T03:56:39.460733+00:00
525
false
We handle the average of zero elements in the very end. \n\n**C++**\n```cpp\nint minimumAverageDifference(vector<int>& nums) {\n vector<long long> ps{0};\n for (int n : nums)\n ps.push_back(n + ps.back());\n long long n = nums.size(), min_i = 0, sum = ps.back(), min_diff = INT_MAX;\n for (int i = 1; i < n; ++i)\n if (int diff = abs(ps[i] / i - (sum - ps[i]) / (n - i)); min_diff > diff) {\n min_diff = diff;\n min_i = i - 1;\n }\n return min_diff <= sum / n ? min_i : n - 1;\n}\n```
5
1
['C']
4
minimum-average-difference
C++ Solution || Easy to Understand
c-solution-easy-to-understand-by-mayanks-eqt0
\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) \n {\n long long int n = nums.size();\n \n long long in
mayanksamadhiya12345
NORMAL
2022-04-30T16:09:31.381849+00:00
2022-04-30T16:09:31.381891+00:00
439
false
```\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) \n {\n long long int n = nums.size();\n \n long long int left_sum = 0;\n long long int right_sum = 0;\n \n priority_queue<pair<long long int,long long int>,vector<pair<long long int,long long int> >,greater<pair<long int,long int> > > pq;\n \n for(int i=0;i<n;i++)\n {\n right_sum += nums[i];\n }\n \n long long int i = 0;\n while(i<n)\n {\n right_sum -= nums[i];\n left_sum += nums[i]; \n \n long long int tmp=0;\n \n if(i < n-1){\n tmp = abs((left_sum/(i+1)) - (right_sum/(n-i-1)));\n \n }\n else\n tmp = (left_sum/(i+1));\n \n pq.push({tmp,i});\n i++;\n \n }\n \n return pq.top().second;\n }\n};\n```
5
0
[]
1
minimum-average-difference
Easy to understand Python Solution
easy-to-understand-python-solution-by-co-89hi
\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n if len(nums) == 1:\n return 0\n min_avg_diff = mat
codonut
NORMAL
2022-04-30T16:02:11.079790+00:00
2022-04-30T16:02:11.079837+00:00
474
false
```\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n if len(nums) == 1:\n return 0\n min_avg_diff = math.inf\n index = -1\n one, two = 0, sum(nums)\n for i in range(0, len(nums)):\n one = one + nums[i]\n two = two - nums[i]\n one_avg = one//(i+1)\n if i == len(nums)-1:\n two_avg = 0\n else:\n two_avg = two//(len(nums)-i-1)\n avg_diff = abs(one_avg-two_avg)\n if avg_diff < min_avg_diff:\n min_avg_diff = avg_diff\n index = i\n return index\n```
5
0
[]
2
minimum-average-difference
Easy C++ Solution
easy-c-solution-by-slow_code-w01b
\tclass Solution {\n\tpublic:\n\t\tint minimumAverageDifference(vector& nums) {\n\t\t\tlong long n = nums.size(),sum = 0,total = accumulate(begin(nums),end(num
Slow_code
NORMAL
2022-04-30T16:01:10.865082+00:00
2022-04-30T16:06:55.841945+00:00
1,597
false
\tclass Solution {\n\tpublic:\n\t\tint minimumAverageDifference(vector<int>& nums) {\n\t\t\tlong long n = nums.size(),sum = 0,total = accumulate(begin(nums),end(nums),0l);\n\t\t\tlong long maxi = LLONG_MAX,res = 0;\n\t\t\tfor(long long i = 0;i<n-1;i++){\n\t\t\t\tsum+=nums[i];\n\t\t\t\tlong long curr = abs(sum/(i+1) - (total-sum)/(n-i-1));\n\t\t\t\tif(curr<maxi) maxi = curr,res = i;\n\t\t\t}\n\n\t\t\treturn maxi>total/n ? n-1:res;\n\t\t}\n\t};
5
0
[]
1
minimum-average-difference
✅ C++ || EASY || DETAILED EXPLAINATION || O(N) O(1)
c-easy-detailed-explaination-on-o1-by-sh-pwun
\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\n long sum = 0,csum = 0;\n int n = nums.size();\n \n
Shababx12
NORMAL
2022-12-04T10:35:03.984454+00:00
2022-12-04T10:35:03.984497+00:00
40
false
```\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\n long sum = 0,csum = 0;\n int n = nums.size();\n \n for(auto x : nums) sum = sum + x;\n \n int min = INT_MAX, ans = 0;\n \n for(int i = 0; i<n; i++){\n csum = csum + nums[i];\n \n int avg1 = csum/(i+1);\n \n if(i == n-1){\n if(avg1<min){\n return n-1;\n }\n else\n break;\n }\n int avg2 = (sum - csum)/(n-i-1);\n if(abs(avg1 - avg2)<min){\n min = abs(avg1-avg2);\n ans = i;\n }\n \n }\n return ans;\n }\n};\n```
4
0
['Array', 'C', 'C++']
0
minimum-average-difference
[Java] Easy Solution || Using Prefix sum || O(n)
java-easy-solution-using-prefix-sum-on-b-w56c
\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n long prefix[] = new long[nums.length];\n long sum = 0;\n \n\t\
MilanMitra2210
NORMAL
2022-12-04T08:17:56.953787+00:00
2022-12-04T08:18:50.008814+00:00
454
false
```\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n long prefix[] = new long[nums.length];\n long sum = 0;\n \n\t\tfor(int i = 0 ; i < nums.length ; i++) {\n\t\t\tprefix[i] = (i == 0)? nums[i] : prefix[i -1] + nums[i];\n sum += nums[i];\n\t\t}\n long avgDiff = 0, minAvgDiff = Long.MAX_VALUE;\n int idx = -1;\n\t\tfor(int i = 0 ; i < nums.length ; i++){\n long post = (i == nums.length - 1)? 0 :((sum - prefix[i]) / (nums.length - i - 1));\n avgDiff = Math.abs((prefix[i] / (i + 1)) - post);\n if(avgDiff < minAvgDiff){\n minAvgDiff = avgDiff;\n idx = i;\n }\n }\n return idx;\n }\n}\n```\n\n**Upvote Please**
4
0
['Java']
0
minimum-average-difference
python_solution
python_solution-by-vivek625-p4kh
\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n n = len(nums)\n sum_num = sum(nums)\n left_Sum = 0\n
vivek625
NORMAL
2022-12-04T05:33:48.706551+00:00
2022-12-04T05:33:48.706582+00:00
436
false
```\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n n = len(nums)\n sum_num = sum(nums)\n left_Sum = 0\n s = [math.inf,math.inf]\n for i , j in enumerate(nums):\n left_Sum += j\n left_avg = left_Sum//(i+1)\n right_avg = (sum_num - left_Sum) // (n-i-1) if (n-i-1) != 0 else 0\n avg = abs(left_avg - right_avg)\n s = min(s,[avg,i])\n return(s[1])\n```
4
0
['Python']
0
minimum-average-difference
✅C++ | ✅Prefix & Suffix Sum | ✅Easy & Efficient
c-prefix-suffix-sum-easy-efficient-by-ya-h2lx
\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) \n {\n int n=nums.size();\n \n long long right_sum = 0;
Yash2arma
NORMAL
2022-12-04T04:59:37.299643+00:00
2022-12-04T04:59:37.299675+00:00
1,253
false
```\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) \n {\n int n=nums.size();\n \n long long right_sum = 0;\n for(auto it:nums) right_sum += it;\n \n int mini = INT_MAX;\n int idx = 0;\n \n long long left_sum = 0;\n \n for(int i=0; i<n; i++)\n {\n left_sum += nums[i];\n right_sum -= nums[i];\n \n long long first = (left_sum/(i+1));\n \n long long last = i<n-1 ? (right_sum/(n-i-1)) : 0;\n \n int diff = abs(first - last);\n \n if(diff < mini)\n {\n mini = diff;\n idx = i;\n }\n }\n \n return idx;\n }\n};\n```
4
0
['Array', 'C', 'Prefix Sum', 'C++']
1
minimum-average-difference
Easy Optimized and Understandable Solution[Prefix Sum] || TC - O(n)
easy-optimized-and-understandable-soluti-qkz0
Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\
AlgoArtisan
NORMAL
2022-12-04T01:56:38.709248+00:00
2022-12-04T02:06:06.191605+00:00
296
false
# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\n\n int maxi=INT_MAX ,res=0,n=nums.size();\n\n long total=0,sum=0;\n\n for(auto x : nums){\n\n total+=x;\n }\n for(int i = 0;i<n-1;i++){\n\n\t\t\tsum+=nums[i];\n\n\t\t\tlong curr = abs(sum/(i+1) - (total-sum)/(n-i-1));\n\n\t\t\tif(curr<maxi) {\n maxi = curr;\n res = i;\n }\n\t\t}\n\n\t\treturn maxi>total/n ? n-1:res;\n \n }\n//Please Upvote :)\n};\n```
4
0
['C++']
0
minimum-average-difference
Use Prefix Sum | CPP SOLUTION
use-prefix-sum-cpp-solution-by-vishwas_7-7qx9
\n int minimumAverageDifference(vector<int>& nums)\n {\n long long int n=nums.size();\n long long int pre[n];\n pre[0]=nums[0];\n
vishwas_7
NORMAL
2022-12-04T00:48:14.720749+00:00
2022-12-04T01:22:46.161969+00:00
52
false
```\n int minimumAverageDifference(vector<int>& nums)\n {\n long long int n=nums.size();\n long long int pre[n];\n pre[0]=nums[0];\n for(int i=1;i<n;i++)\n {\n pre[i]=pre[i-1]+nums[i]; //Here we are making prefix sum array whic reduce the complexity of finding sum for each index ...\n }\n int average=INT32_MAX; //for comparison\n \n int a,b,index;\n for(int i=0;i<n;i++)\n {\n a=pre[i]/(i+1);\n if(i!=(n-1)) //important condition because at every n-1 index our n-i-1 condition gives 0 value which will return runtime error exception . from explanation we are able to understood that at each n-1 index b==0\n b=(pre[n-1]-pre[i])/(n-i-1);\n else\n b=0;\n long long int maxi=abs(a-b);\n \n if(maxi<average)\n {\n if(maxi==0)\n {\n return i;//this is lowest difference possible hence we are returning the index of that index\n }\n else\n {\n average=maxi;\n index=i;\n }\n \n }\n }\n return index;\n \n }``\n```
4
0
[]
0
minimum-average-difference
C++ || Two Solutions || Prefix Sum || Simple Easy Solution
c-two-solutions-prefix-sum-simple-easy-s-r1sf
class Solution {\npublic:\n//Time Complexicity: O(N)\n//Sapce Complexicity: O(N)\n\n\n\n int minimumAverageDifference(vector& nums) {\n int n=nums.siz
ritik_pr3003
NORMAL
2022-05-08T12:59:56.573641+00:00
2022-05-28T10:36:36.019334+00:00
284
false
class Solution {\npublic:\n//Time Complexicity: O(N)\n//Sapce Complexicity: O(N)\n\n\n\n int minimumAverageDifference(vector<int>& nums) {\n int n=nums.size();\n vector <long long int> v(n,0);\n v[0]=nums[0];\n for(int i=1; i<n; i++){\n v[i]=v[i-1]+nums[i];\n }\n int ans=0;\n int max=INT_MAX;\n for(int i=0; i<n-1; i++){\n long long int x=v[i]/(i+1);\n long long int y=v[n-1]-v[i];\n y=y/(n-i-1);\n if(max>abs(y-x)){\n ans=i;\n max=abs(x-y);\n }\n }\n if(max>v[n-1]/n){\n ans=n-1;\n }\n return ans;\n }\n};\n//Time Complexicity: O(N)\n//Space Complexicity: O(1)\n\nclass Solution {\npublic:\n \n int minimumAverageDifference(vector<int>& nums) {\n int n=nums.size();\n long long int right=accumulate(nums.begin(),nums.end(),0ll);\n long long int left=0;\n long long int ans=0;\n long long int max=INT_MAX;\n for(int i=0; i<n-1; i++){\n left+=nums[i];\n long long int x=left/(i+1);\n long long int y=right-left;\n y=y/(n-i-1);\n long long int j=abs(x-y);\n if(max>abs(y-x)){\n max=j;\n ans=i;\n }\n }\n if(max>(left+nums[n-1])/n){\n ans=n-1;\n }\n return ans;\n }\n};\n
4
0
['C', 'Prefix Sum']
0
minimum-average-difference
C++ || Use suffix sum || Easy to understand
c-use-suffix-sum-easy-to-understand-by-s-e0qk
\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\n long long int left = 0;\n long long int right = 0;\n f
shm_47
NORMAL
2022-04-30T16:09:51.891371+00:00
2022-04-30T16:09:51.891405+00:00
234
false
```\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\n long long int left = 0;\n long long int right = 0;\n for(auto i: nums)\n right += i;\n \n int n = nums.size();\n int mn = INT_MAX;\n int idx = 0;\n for(int i=0; i<nums.size(); i++){\n left += nums[i];\n right -= nums[i];\n // cout<< left << "\\t" << right << "\\t" <<left/(i+1) << "\\t" << right/(n-1-i) << endl;\n \n int diff = 0;\n if(i==n-1)\n diff = left/(i+1);\n else\n diff = abs(left/(i+1) - right/(n-1-i));\n \n if(diff < mn){\n mn = diff;\n idx = i;\n }\n }\n \n return idx;\n }\n};\n```
4
1
['C']
0
minimum-average-difference
python easy solution
python-easy-solution-by-akaghosting-18q6
\tclass Solution:\n\t\tdef minimumAverageDifference(self, nums: List[int]) -> int:\n\t\t\tminiAverage = float("inf")\n\t\t\tleft = 0\n\t\t\ts = sum(nums)\n\t\t\
akaghosting
NORMAL
2022-04-30T16:02:06.156685+00:00
2022-12-04T17:30:25.307530+00:00
719
false
\tclass Solution:\n\t\tdef minimumAverageDifference(self, nums: List[int]) -> int:\n\t\t\tminiAverage = float("inf")\n\t\t\tleft = 0\n\t\t\ts = sum(nums)\n\t\t\tres = 0\n\t\t\tfor i, num in enumerate(nums):\n\t\t\t\tleft += num\n\t\t\t\tright = s - left\n\t\t\t\tif i != len(nums) - 1:\n\t\t\t\t\tif abs(left // (i + 1) - right // (len(nums) - i - 1)) < miniAverage:\n\t\t\t\t\t\tminiAverage = abs(left // (i + 1) - right // (len(nums) - i - 1))\n\t\t\t\t\t\tres = i\n\t\t\t\telse:\n\t\t\t\t\tif left // (i + 1) < miniAverage:\n\t\t\t\t\t\tres = i\n\t\t\treturn res
4
0
['Python3']
2
minimum-average-difference
Java | Prefix sum
java-prefix-sum-by-aaveshk-ogrr
The only catch here is to test the case taking all in the first average separetely else division by 0 exception will be encountered\n\nclass Solution\n{\n pu
aaveshk
NORMAL
2022-04-30T16:01:15.689786+00:00
2022-04-30T16:01:15.689843+00:00
1,606
false
The only catch here is to test the case taking all in the first average separetely else division by 0 exception will be encountered\n```\nclass Solution\n{\n public int minimumAverageDifference(int[] nums)\n {\n int N = nums.length, id = 0;\n long min = Integer.MAX_VALUE;\n long[] pre = new long[N];\n pre[0] = nums[0];\n for(int i = 1; i < N; i++)\n pre[i] = pre[i-1]+nums[i];\n for(int i = 0; i < N-1; i++)\n {\n long diff = (long)(Math.abs(Math.round(pre[i]/(i+1) - Math.round((pre[N-1]-pre[i])/(N-i-1)))));\n if(diff < min)\n {\n id = i;\n min = diff;\n }\n }\n if(min > pre[N-1]/N) // Taking all on the first/left\n return N-1;\n return id;\n }\n}\n```
4
0
['Java']
2
minimum-average-difference
Simple Prefix Sum || C++ Solution
simple-prefix-sum-c-solution-by-shah4772-uuk1
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
shah4772
NORMAL
2023-07-12T04:25:18.777317+00:00
2023-07-12T04:25:18.777337+00:00
15
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 minimumAverageDifference(vector<int>& nums) {\n long long totalSum = 0;\n int n = nums.size();\n if(n==1)return 0;\n for(auto x:nums){\n totalSum += x; \n }\n int ind = 0,mini=INT_MAX;\n \n long long stSum = 0;\n for(int i=1;i<=n;i++){\n stSum += nums[i-1];\n long long enSum = totalSum-stSum;\n int avg = 0;\n if(n-i==0){\n avg = stSum/i;\n }else\n avg = abs((stSum/i) - (enSum/(n-i)));\n if(avg<mini){\n mini = avg;\n ind = i-1;\n }\n }\n return ind;\n }\n};\n```
3
0
['Array', 'Prefix Sum', 'C++']
0
minimum-average-difference
Easy python Solution || using prefix sum Run time 75%
easy-python-solution-using-prefix-sum-ru-6b30
Code\n\nclass Solution(object):\n def minimumAverageDifference(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n
Lalithkiran
NORMAL
2023-03-08T18:22:07.313477+00:00
2023-03-08T18:22:07.313515+00:00
21
false
# Code\n```\nclass Solution(object):\n def minimumAverageDifference(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n t_sm=sum(nums) #total sum\n mx_idx=len(nums) #last index\n st_sm=0 \n mn_val=t_sm//len(nums)\n mn_idx=len(nums)-1\n for i in range(len(nums)-1):\n t_sm-=nums[i]\n st_sm+=nums[i]\n mx_idx-=1\n val=abs((st_sm//(i+1)) - (t_sm//mx_idx))\n old_mn=mn_val\n mn_val=min(mn_val,val)\n if mn_val==val:\n if old_mn==mn_val:\n mn_idx=min(i,mn_idx)\n else:\n mn_idx=i\n return mn_idx\n```
3
0
['Array', 'Prefix Sum', 'Python']
0
minimum-average-difference
C++ easy to understand Solution Beats 100%
c-easy-to-understand-solution-beats-100-g5ur1
Intuition\nDo the sum of all elements and observe.\n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity:\nO(n)\n\n
HimanshuPantwal
NORMAL
2022-12-05T03:22:14.739303+00:00
2022-12-05T03:22:14.739346+00:00
380
false
# Intuition\nDo the sum of all elements and observe.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\n long sum=0,s=0;\n for(int j=0;j<nums.size();j++)\n {\n s+=nums[j];\n }\n long min=INT_MAX;\n int index=-1;\n for(int i=0;i<nums.size();i++)\n {\n long avg=0;\n sum+=nums[i];\n s-=nums[i];\n if(nums.size()-i-1>0)\n {\n avg=sum/(i+1)-s/(nums.size()-i-1);\n avg=abs(avg);\n }\n else{\n avg=abs(sum/(i+1));\n }\n if(avg<min)\n {\n min=avg;\n index=i;\n }\n }\n return index;\n }\n};\n```
3
0
['C++']
1
minimum-average-difference
Java Most Possible Solution
java-most-possible-solution-by-janhvi__2-1lc1
\nclass Solution {\n public int minimumAverageDifference(int[] n) {\n long sum=0;\n int i;\n for(i=0;i<n.length;i++)\n sum+=n
Janhvi__28
NORMAL
2022-12-04T17:37:40.710010+00:00
2022-12-04T17:37:40.710045+00:00
44
false
```\nclass Solution {\n public int minimumAverageDifference(int[] n) {\n long sum=0;\n int i;\n for(i=0;i<n.length;i++)\n sum+=n[i];\n long x=0;;\n int min=Integer.MAX_VALUE;\n int result=0;\n for(i=0;i<n.length;i++){\n x=x+n[i];\n sum=sum-n[i];\n int a=(int)(x/(i+1));\n int b=(i==n.length-1)?0:(int)(sum/(n.length-i-1));\n if(Math.abs(a-b) < min){\n min=Math.abs(a-b);\n result=i;\n }\n }\n return result;\n }\n}\n```
3
0
['Java']
0
minimum-average-difference
Java 🔥 Solution ✅
java-solution-by-beri_prince-w36h
Code\n\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n int n = nums.length;\n int ans = -1;\n int minDiff = Int
Beri_Prince
NORMAL
2022-12-04T16:38:29.243007+00:00
2022-12-04T16:38:29.243046+00:00
137
false
# Code\n```\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n int n = nums.length;\n int ans = -1;\n int minDiff = Integer.MAX_VALUE;\n\n long preSum = 0, totalSum = 0;\n for(int num: nums){\n totalSum += num;\n }\n\n for(int i = 0; i < n; i++){\n preSum += nums[i];\n long leftAvg = preSum / (i + 1);\n long rightAvg = (totalSum - preSum);\n if(i != n - 1){\n rightAvg /= (n - i - 1);\n }\n\n int currDiff = (int) Math.abs(leftAvg - rightAvg);\n if(currDiff < minDiff){\n ans = i;\n minDiff = currDiff;\n }\n }\n\n return ans;\n }\n}\n```
3
0
['Array', 'Prefix Sum', 'Java']
0
minimum-average-difference
Java | Beats 100% | Prefix Sum | Explained
java-beats-100-prefix-sum-explained-by-n-tqoh
\n\n# Intuition\nTo calculate the average between range [x:y] in O(1) we can use a prefix sum.\n\nThe sum of an interval [x:y] (inclusive) will be prefix[y] - p
nadaralp
NORMAL
2022-12-04T13:55:42.412948+00:00
2022-12-04T13:58:06.999683+00:00
696
false
![image.png](https://assets.leetcode.com/users/images/744f5b68-e3d2-498c-b30a-49344e09bd48_1670161849.0439353.png)\n\n# Intuition\nTo calculate the average between range `[x:y]` in O(1) we can use a prefix sum.\n\nThe sum of an interval `[x:y]` (inclusive) will be `prefix[y] - prefix[x-1]` and we would divide by the range of the interval which is `y-x+1` assuming y > x.\n\nTo avoid edge cases while subtracting `prefix[x-1]` we will initialize the array with a buffer of 1, so we can type the code more easily.\n\nNote: the divisor is of type `double` so if we divide by `0d` we don\'t throw a zero division exception.\n\n\n\n# Code\n```\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n int n = nums.length;\n double[] prefix = new double[n + 1]; // prefix[1] is sum up to i=1 exclusive [0, i)\n\n // A = [2, 3, 5] //\n // PS = [0, 2, 5, 10]\n for (int i = 0; i < n; i++) {\n prefix[i + 1] = prefix[i] + nums[i];\n }\n\n int bestIndex = 0;\n int best = Integer.MAX_VALUE;\n\n for (int i = 0; i < n; i++) {\n int prefixAverage = (int) Math.floor(prefix[i + 1] / (i + 1));\n int suffixAverage = (int) Math.floor((prefix[n] - prefix[i + 1]) / (n - i - 1));\n int averageDifference = Math.abs(\n // taking sum up to index i inclusive (i+1 elements)\n prefixAverage -\n // taking sum from i+1:n (n-i elements)\n suffixAverage\n );\n if (averageDifference < best) {\n best = averageDifference;\n bestIndex = i;\n }\n }\n\n return bestIndex;\n }\n}\n```
3
0
['Java']
0
minimum-average-difference
Python | Easy Solution | Lists | Prefix Sum
python-easy-solution-lists-prefix-sum-by-i150
CODE 1 (BETTER)\n\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n first = [nums[0]]\n second = nums[1:]\n\n
atharva77
NORMAL
2022-12-04T04:08:38.170533+00:00
2022-12-04T05:05:34.326648+00:00
193
false
# CODE 1 (BETTER)\n```\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n first = [nums[0]]\n second = nums[1:]\n\n if len(nums) == 1:\n return 0\n\n v1 = sum(first)\n v2 = sum(second)\n l1 = 1\n l2 = len(nums) - 1\n\n currDiff = abs((v1 // l1) - (v2 // l2))\n currIndex = 0\n\n for i in range(1, len(nums)-1):\n if l1 == 0:\n v1 = 0\n l1 = 0\n else:\n v1 = (v1 + nums[i])\n l1 += 1\n\n\n if l2 == 0:\n v2 = 0\n l2 = 0\n else:\n v2 = (v2 - nums[i])\n l2 -= 1\n\n\n if currDiff > abs((v1 // l1) - (v2 // l2)):\n currDiff = abs((v1 // l1) - (v2 // l2))\n currIndex = i\n\n v1 = sum(nums[:]) // len(nums[:])\n\n if currDiff > abs(v1 - 0):\n currDiff = abs(v1 - 0)\n currIndex = len(nums)-1\n\n return currIndex\n```\n# CODE 2 (LAZY)\n```\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n first = [nums[0]]\n second = nums[1:]\n if len(nums) == 1:\n return 0\n v1 = sum(first)\n v2 = sum(second)\n currDiff = abs((v1 // len(first)) - (v2 // len(second)))\n currIndex = 0\n for i in range(1, len(nums)-1):\n first.append(nums[i])\n second.pop(0)\n # print(first, second)\n if len(first) == 0:\n v1 = 0\n l1 = 0\n else:\n v1 = (v1 + nums[i])\n l1 = len(first)\n if len(second) == 0:\n v2 = 0\n l2 = 0\n else:\n v2 = (v2 - nums[i])\n l2 = len(second)\n # print(v1, v2)\n if currDiff > abs((v1 // l1) - (v2 // l2)):\n\n currDiff = abs((v1 // l1) - (v2 // l2))\n currIndex = i\n v1 = sum(nums[:]) // len(nums[:])\n if currDiff > abs(v1 - 0):\n currDiff = abs(v1 - 0)\n currIndex = len(nums)-1\n return currIndex\n```
3
0
['Array', 'Prefix Sum', 'Python3']
1
minimum-average-difference
minimum-average-difference
minimum-average-difference-by-pravinglkp-q09b
\n\n# Complexity\n- Time complexity:O(n)\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
pravinglkp
NORMAL
2022-12-04T01:43:01.201407+00:00
2022-12-04T01:43:01.201441+00:00
357
false
\n\n# Complexity\n- Time complexity:O(n)\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 {\n public int minimumAverageDifference(int[] nums) {\n \n long sum=0;\n for(int x:nums) sum+=x;\n int res=0;\n long min=Long.MAX_VALUE;\n long curr=0;\n for(int i=0;i<nums.length-1;i++){\n curr+=nums[i];\n sum-=nums[i];\n \n long diff=Math.abs(curr/(i+1)-sum/(nums.length-i-1));\n \n if(diff<min){\n min=diff;\n res=i;\n }\n }\n curr+=nums[nums.length-1];\n if(curr/nums.length<min){\n res=nums.length-1;\n }\n return res;\n \n }\n}\n\n\n```
3
0
['Java']
0
minimum-average-difference
🗓️ Daily LeetCoding Challenge December, Day 4
daily-leetcoding-challenge-december-day-fxq0y
This problem is the Daily LeetCoding Challenge for December, Day 4. Feel free to share anything related to this problem here! You can ask questions, discuss wha
leetcode
OFFICIAL
2022-12-04T00:00:30.635266+00:00
2022-12-04T00:00:30.635339+00:00
1,829
false
This problem is the Daily LeetCoding Challenge for December, Day 4. Feel free to share anything related to this problem here! You can ask questions, discuss what you've learned from this problem, or show off how many days of streak you've made! --- If you'd like to share a detailed solution to the problem, please create a new post in the discuss section and provide - **Detailed Explanations**: Describe the algorithm you used to solve this problem. Include any insights you used to solve this problem. - **Images** that help explain the algorithm. - **Language and Code** you used to pass the problem. - **Time and Space complexity analysis**. --- **📌 Do you want to learn the problem thoroughly?** Read [**⭐ LeetCode Official Solution⭐**](https://leetcode.com/problems/minimum-average-difference/solution) to learn the 3 approaches to the problem with detailed explanations to the algorithms, codes, and complexity analysis. <details> <summary> Spoiler Alert! We'll explain this 0 approach in the official solution</summary> </details> If you're new to Daily LeetCoding Challenge, [**check out this post**](https://leetcode.com/discuss/general-discussion/655704/)! --- <br> <p align="center"> <a href="https://leetcode.com/subscribe/?ref=ex_dc" target="_blank"> <img src="https://assets.leetcode.com/static_assets/marketing/daily_leetcoding_banner.png" width="560px" /> </a> </p> <br>
3
0
[]
48
minimum-average-difference
Easy Cpp solution using Prefix and Suffix sum
easy-cpp-solution-using-prefix-and-suffi-6qfh
```\nclass Solution {\npublic:\n int minimumAverageDifference(vector& nums) {\n int size=nums.size();\n vector pref(size),suff(size);\n
aditya_sinha_
NORMAL
2022-05-23T19:15:56.406984+00:00
2022-05-23T19:15:56.407037+00:00
113
false
```\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\n int size=nums.size();\n vector<long long int> pref(size),suff(size);\n pref[0]=nums[0];\n suff[size-1]=0;\n long long int sum=nums[0];\n for(int i=1;i<size;i++){\n sum +=nums[i];\n pref[i]=sum/(i+1);\n }\n sum=0;\n for(int i=size-2,k=1;i>=0;i--,k++){\n sum +=nums[i+1];\n suff[i]=sum/k;\n }\n int m=INT_MAX,ind=0,temp;\n for(int i=0;i<size;i++){\n temp=abs(pref[i]-suff[i]);\n if(m>temp){\n m=temp;\n ind=i;\n }\n }\n return ind;\n }\n};
3
0
[]
1
minimum-average-difference
Easy C++ | Prefix Array | O(N) time
easy-c-prefix-array-on-time-by-rgarg2580-40ax
\n\n\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int> &vec) {\n long long n = vec.size();\n vector<long long> pref(n, 0);\
rgarg2580
NORMAL
2022-04-30T16:25:07.905059+00:00
2022-04-30T16:25:07.905089+00:00
76
false
\n\n```\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int> &vec) {\n long long n = vec.size();\n vector<long long> pref(n, 0);\n pref[0] = vec[0];\n for(long long i=1; i<n; i++) {\n pref[i] = pref[i-1] + vec[i];\n }\n \n int ans = -1;\n long long minDiff = INT_MAX;\n for(int i=0; i<n; i++) {\n long long left = pref[i]/(i+1);\n long long right = 0;\n if(n-i-1 != 0) right = (pref[n-1] - pref[i])/(n-i-1);\n long long diff = abs(left-right);\n if(diff < minDiff) {\n minDiff = diff;\n ans = i;\n }\n }\n return ans;\n }\n};\n```
3
0
['C']
0
minimum-average-difference
Java|| Easy to Understand || main thing is to handle the last index
java-easy-to-understand-main-thing-is-to-8568
You can skip the arr part that is redundant that is used only for i/o purpose else you can ommit it.\n\nclass Solution {\n public int minimumAverageDifferenc
ashwinj_984
NORMAL
2022-04-30T16:08:02.331154+00:00
2022-05-02T12:16:00.867283+00:00
542
false
You can skip the `arr` part that is redundant that is used only for i/o purpose else you can ommit it.\n```\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n if(nums.length == 1){\n return 0;\n }\n int idx = -1;\n long min = Integer.MAX_VALUE;\n long suml = nums[0];\n long sumr = 0;\n for(int i = 1; i < nums.length; i++){\n sumr += nums[i];\n }\n int i = 1;\n int calc = 0;\n int left = 1;\n int right = nums.length - left;\n long[] arr = new long[nums.length];\n while(i < nums.length){\n long diff = Math.abs((suml/left) - (sumr/right));\n arr[calc] = diff;\n if(diff < min){\n min = diff;\n idx = calc;\n }\n suml += nums[i];\n sumr -= nums[i];\n left++;\n right--;\n calc++;\n i++;\n }\n arr[calc] = suml/nums.length;\n if(arr[calc] < min){\n min = arr[calc];\n idx = nums.length - 1;\n }\n // for(i = 0; i < nums.length; i++){\n // System.out.println(arr[i]);\n // }\n return (int)idx;\n }\n}\n```
3
0
['Java']
0
minimum-average-difference
scala
scala-by-nikiforo-xil8
scala\ndef minimumAverageDifference(nums: Array[Int]): Int = {\n val list = nums.map(_.toLong).toList\n goMinAv(list, 0, 0, list.sum, nums.length, Int.MaxValu
nikiforo
NORMAL
2022-04-30T16:04:32.155837+00:00
2022-04-30T16:04:32.155886+00:00
70
false
```scala\ndef minimumAverageDifference(nums: Array[Int]): Int = {\n val list = nums.map(_.toLong).toList\n goMinAv(list, 0, 0, list.sum, nums.length, Int.MaxValue, 0)\n}\n\ndef goMinAv(nums: List[Long], leftSum: Long, ind: Int, rightSum: Long, rightCount: Int, minimum: Long, minimumInd: Int): Int =\n nums match {\n case Nil => minimumInd\n case h :: tail =>\n val lSum = leftSum + h\n val rSum = rightSum - h\n val lCount = ind + 1\n val rCount = rightCount - 1\n\n val rAvg = if(rCount == 0) 0 else rSum / rCount\n val avDiff = math.abs(lSum / lCount - rAvg)\n val (min, minInd) = if(avDiff < minimum) (avDiff, ind) else (minimum, minimumInd)\n\n goMinAv(tail, lSum, lCount, rSum, rCount, min, minInd)\n }\n ```
3
0
['Scala']
0
minimum-average-difference
C++ || SIMPLE
c-simple-by-s_kr007-d31d
\nclass Solution {\npublic:\n #define ll long long\n int minimumAverageDifference(vector<int>& nums) {\n int n = nums.size();\n int val = IN
s_kr007
NORMAL
2022-04-30T16:02:06.034162+00:00
2022-04-30T16:02:40.927574+00:00
268
false
```\nclass Solution {\npublic:\n #define ll long long\n int minimumAverageDifference(vector<int>& nums) {\n int n = nums.size();\n int val = INT_MAX;\n int idx = 0;\n \n ll sum = 0,cur = 0;\n for(int i:nums)sum += i;\n \n for(int i=0;i<n;i++){\n cur += nums[i];\n sum -= nums[i];\n \n ll c_val = 0;\n if(i == n-1){\n c_val = cur/(i+1);\n }\n else c_val = abs((cur)/(i+1) - ((sum)/(n-i-1)));\n if(c_val < val){\n val = c_val;\n idx = i;\n }\n } \n return idx;\n }\n};\n```
3
0
['C']
0
minimum-average-difference
prefix sum method
prefix-sum-method-by-theabbie-msji
\nclass Solution:\n def getDiff(self, prefix, i, n):\n l = (prefix[i + 1] - prefix[0])\n r = prefix[-1] - l\n l = l // (i + 1)\n
theabbie
NORMAL
2022-04-30T16:00:46.100097+00:00
2022-04-30T16:00:46.100144+00:00
1,698
false
```\nclass Solution:\n def getDiff(self, prefix, i, n):\n l = (prefix[i + 1] - prefix[0])\n r = prefix[-1] - l\n l = l // (i + 1)\n r = r // (n - i - 1) if i < n - 1 else 0\n return abs(l - r)\n \n def minimumAverageDifference(self, nums: List[int]) -> int:\n n = len(nums)\n prefix = [0]\n for i in range(n):\n prefix.append(prefix[-1] + nums[i])\n return min(range(n), key = lambda i: self.getDiff(prefix, i, n))\n```
3
0
['Python']
0
minimum-average-difference
Easy Java prefix sum solution
easy-java-prefix-sum-solution-by-suraj24-wv6c
Intuition\nPrefix sum approach.\n\n# Approach\n1) Uses Prefix Sum Array approach\n2) prefixSum[i] = prefixSum[i - 1] + arr[i];\n\n# Complexity\n- Time complexi
suraj2403
NORMAL
2023-03-19T12:21:15.153107+00:00
2023-03-19T12:21:15.153154+00:00
42
false
# Intuition\nPrefix sum approach.\n\n# Approach\n1) Uses Prefix Sum Array approach\n2) prefixSum[i] = prefixSum[i - 1] + arr[i];\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 minimumAverageDifference(int[] nums) {\n \n int len=nums.length;\nlong sum=0;\nint index=0;;\nlong min=Integer.MAX_VALUE;\nlong leftSum=0,rightSum=0;\n\n\nfor(int i=0;i<len;i++){\n sum+=nums[i];\n}\n\nfor(int i=0;i<len;i++){\n leftSum+= nums[i];\n \n\nlong avgLeftSum=leftSum/(i+1);\n\nrightSum=sum-leftSum;\nlong avgRightSum=0;\n\n if(rightSum!=0){\n avgRightSum=rightSum/(len-i-1);\n }\n\n\nlong diff=Math.abs(avgLeftSum-avgRightSum);\n\nif(diff<min){\n min=diff;\n index=i;\n}\n}\n\nreturn index;\n }\n}\n```
2
0
['Prefix Sum', 'Java']
0
minimum-average-difference
Easy To Understand & Fast Approach with eliminating TLE using Sliding Window
easy-to-understand-fast-approach-with-el-du9y
Intuition\n Describe your first thoughts on how to solve this problem. \nIn order to answer this issue, we must add up two different array segments, find their
yash_visavadia
NORMAL
2023-02-05T18:17:56.993733+00:00
2023-02-05T18:17:56.993774+00:00
23
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn ***order*** to ***answer*** this ***issue***, we ***must add*** up two different array ***segments***, find ***their*** average, then ***reduce*** the ****absolute**** ***difference*** ***between*** them.\n\n***Therefore***, we will ***first compute*** the ***total*** of the left portion ***using*** left sum, then we will ***get its*** average, and ***finally***, we can do the same for the right portion ***using*** right sum, after which we will ***determine*** which is the ***least absolute*** difference to store in mini.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere we are simply using technique same as ***sliding window*** technique\n\n# Complexity\n- Time complexity:O(n)\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:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n size = len(nums)\n mini = sys.maxsize\n ind = 0\n left_sum = 0\n right_sum = sum(nums)\n for i in range(size):\n left_sum += nums[i]\n right_sum -= nums[i]\n\n st = left_sum // (i + 1)\n if i == size - 1:\n end = 0\n else:\n end = right_sum // (size - (i + 1))\n\n if mini > abs(st - end):\n mini = abs(st - end)\n ind = i\n return ind\n```
2
0
['Array', 'Sliding Window', 'Python3']
0
minimum-average-difference
✅C++ | ✅Prefix & Suffix Sum | ✅Easy & Efficient
c-prefix-suffix-sum-easy-efficient-by-ar-huc3
\n#CODE\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\n
arunava_42
NORMAL
2023-02-04T07:00:09.274595+00:00
2023-02-04T07:00:09.274706+00:00
20
false
```\n#CODE\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\n long long int TotalSum=0,n=nums.size(),mini=INT_MAX,currSum=0,sumLeft=0,diff=0;\n int idx=0;\n for(int i=0;i<n;i++){\n TotalSum+=nums[i];\n }\n if(n==1){\n return 0;\n }\n for(int i=0;i<n;i++){\n currSum+=nums[i];\n sumLeft=TotalSum-currSum;\n if(sumLeft==0){\n diff=floor(currSum/(i+1));\n }else{\n diff=abs((currSum/(i+1))-(sumLeft/(n-i-1)));\n }\n if(mini>diff){\n mini=diff;\n idx=i;\n }\n }\n return idx;\n }\n};\n```\n\n![c668b758-003d-4e6f-a374-c128c2ef83e6_1655058432.5612516.jpeg](https://assets.leetcode.com/users/images/372db7f4-6604-4176-adea-a17e0620349b_1675493896.8659327.jpeg)\n
2
0
['C++']
0
minimum-average-difference
Concise Prefix Sum | C++
concise-prefix-sum-c-by-tusharbhart-otsj
\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\n long long mn = INT_MAX, ans = 0, ls = 0, rs = 0, n = nums.size();\n
TusharBhart
NORMAL
2022-12-31T16:16:17.470017+00:00
2022-12-31T16:16:17.470055+00:00
253
false
```\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\n long long mn = INT_MAX, ans = 0, ls = 0, rs = 0, n = nums.size();\n for(int i : nums) rs += i;\n\n for(int i=0; i<n-1; i++) {\n ls += nums[i];\n rs -= nums[i];\n int a = ls / (i + 1);\n int b = rs / (n - i - 1);\n\n if(abs(a - b) < mn) mn = abs(a - b), ans = i;\n }\n return (ls + nums.back()) / n < mn ? n - 1 : ans;\n }\n};\n```
2
0
['Prefix Sum', 'C++']
0
minimum-average-difference
python, calculate sum(list) once, O(n); test case [0,1,0,1,0,1] explained
python-calculate-sumlist-once-on-test-ca-lk0j
CAUTION:\nIf you didn\'t pass test case [0,1,0,1,0,1], you might want to read the following sentence from the description again. :-P\n\nBoth averages should be
nov05
NORMAL
2022-12-05T06:19:25.286974+00:00
2022-12-05T06:19:25.287008+00:00
160
false
**CAUTION:**\nIf you didn\'t pass test case `[0,1,0,1,0,1]`, you might want to read the following sentence from the description again. :-P\n```\nBoth averages should be rounded down to the nearest integer.\n```\nhttps://leetcode.com/submissions/detail/854862152/\n```\nRuntime: 1684 ms, faster than 72.91% of Python3 online submissions for Minimum Average Difference.\nMemory Usage: 24.8 MB, less than 95.93% of Python3 online submissions for Minimum Average Difference.\n```\n```\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n l = len(nums)\n if l==1: return 0\n \n s1, s2 = nums[0], sum(nums[1:])\n i_smallest, abs_smallest = 0, abs(s1//1 - s2//(l-1))\n for i in range(1,l):\n n = nums[i]\n l1, l2 = i+1, l-i-1\n s1 += n; s2 -= n\n if i!=l-1:\n abs_curr = abs(s1//l1 - s2//l2)\n else:\n abs_curr = s1//l1\n if abs_curr<abs_smallest:\n abs_smallest = abs_curr\n i_smallest = i\n \n return i_smallest \n```\n\n
2
0
['Python']
0
minimum-average-difference
Prefix Sum simple c++ solution
prefix-sum-simple-c-solution-by-akshitas-lpez
//T.C -> O(n) as we have traversed through a single loop\n\t\t//S.C -> O(n) as we have usead extra space for prefixSum vector\n\t\t\n\t\t//Approach -> we will s
akshitasharma7
NORMAL
2022-12-04T22:10:27.478155+00:00
2022-12-04T22:10:27.478190+00:00
22
false
//T.C -> O(n) as we have traversed through a single loop\n\t\t//S.C -> O(n) as we have usead extra space for prefixSum vector\n\t\t\n\t\t//Approach -> we will store prefix sum for each index in a vector and after that for every index we will keep on subtracting prefixSum at that index from total Sum and keep taking diffrrence of their averages. When this difference becomes less than minimum difference than we will update our index to that current index..\n\t\t\n\t\t\n\t\tif(nums.size()==1){\n return 0;\n }\n \n vector<long long int>prefixSum(nums.size());\n prefixSum[0]=nums[0];\n long long int total=nums[0];\n \n for(int i=1;i<nums.size();i++){\n prefixSum[i]=nums[i]+prefixSum[i-1];\n total+=nums[i];\n }\n \n int min_diff=INT_MAX;\n int index=0;\n \n \n for(int i=0;i<nums.size()-1;i++){\n int val1=prefixSum[i]/(i+1);\n int val2=(total-prefixSum[i])/(nums.size()-i-1);\n \n if(abs(val1-val2)<min_diff){\n min_diff=abs(val1-val2);\n index=i;\n }\n \n }\n \n int last=total/nums.size();\n if(last<min_diff){\n return nums.size()-1;\n }\n \n return index;
2
0
['C', 'Prefix Sum']
0
minimum-average-difference
C++ O(n) time and O(1) Space with Prefix Sum
c-on-time-and-o1-space-with-prefix-sum-b-oxrz
\nApproach :\n\n Find sum as sum of all n elements and keep a prefSum for storing sum till i index.\n Use prefSum for finding sum ofi+1 elements which is prefSu
krunal_078
NORMAL
2022-12-04T20:18:53.325904+00:00
2022-12-04T20:36:05.371063+00:00
39
false
\n`Approach : `\n\n* Find sum as `sum` of all n elements and keep a prefSum for storing sum till i index.\n* Use `prefSum ` for finding sum of` i+1` elements which is prefSum it self and `sum-prefSum` for finding sum of remaining `n-i` elements.\n* Check for edge case when `i = n-1` and find minimum average difference.\n* Now iterate again to find minimum index with the minimum average difference.\n\n**Time : O(n)\nSpace : O(1)**\n\n\n```\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& v){\n long long sum = 0, prefSum = 0;\n int n = v.size();\n long long mn = 1e9;\n for(auto &ele:v) sum += ele;\n for(int i=0;i<n;i++){\n prefSum += v[i];\n if(i!=n-1)\n mn = min(mn,abs(prefSum/(i+1) - (sum-prefSum)/(n-i-1)));\n else mn = min(mn,prefSum/(i+1));\n }\n prefSum = 0;\n for(int i=0;i<n;i++){\n prefSum += v[i];\n long long val = 0;\n if(i!=n-1)\n val = abs(prefSum/(i+1) - (sum - prefSum)/(n-i-1));\n else val = prefSum/(i+1);\n if(val==mn) return i;\n }\n return -1;\n }\n};\n```
2
0
['Array', 'C', 'Prefix Sum', 'C++']
0
minimum-average-difference
Easy JAVA Solution
easy-java-solution-by-shivgup_2000-he72
Approach\n Basic approach\n\n# Complexity\n- Time complexity:\n O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:\n O(1) Add your
Shivgup_2000
NORMAL
2022-12-04T17:29:52.253009+00:00
2022-12-04T17:29:52.253056+00:00
14
false
# Approach\n Basic approach\n\n# Complexity\n- Time complexity:\n O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n O(1)<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minimumAverageDifference(int[] n) {\n long sume=0;\n int i;\n for(i=0;i<n.length;i++)\n sume+=n[i];\n long sums=0;;\n int min=Integer.MAX_VALUE;\n int ind=0;\n for(i=0;i<n.length;i++){\n sums=sums+n[i];\n sume=sume-n[i];\n int a=(int)(sums/(i+1));\n int b=(i==n.length-1)?0:(int)(sume/(n.length-i-1));\n if(Math.abs(a-b) < min){\n min=Math.abs(a-b);\n ind=i;\n }\n }\n return ind;\n }\n}\n```
2
0
['Java']
0
minimum-average-difference
JAVA | 3 solutions | Brute -> Optimal ✅
java-3-solutions-brute-optimal-by-sourin-e9sp
Please Upvote :D\n##### 1. Brute force approach:\nCalculating the right and left average using nested loops for every index of nums.\njava []\nclass Solution {\
sourin_bruh
NORMAL
2022-12-04T17:14:39.380639+00:00
2022-12-07T13:29:46.268021+00:00
55
false
### **Please Upvote** :D\n##### 1. Brute force approach:\nCalculating the right and left average using nested loops for every index of nums.\n``` java []\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n int n = nums.length;\n int minAvgDiff = Integer.MAX_VALUE, ans = -1;\n\n for (int i = 0; i < n; i++) {\n int leftAvg = 0;\n\n for (int left = 0; left <= i; left++) {\n leftAvg += nums[left];\n }\n\n leftAvg /= (i + 1);\n\n int rightAvg = 0;\n\n for (int right = i + 1; right < n; right++) {\n rightAvg += nums[right];\n }\n\n if (i != n - 1) rightAvg /= (n - i - 1);\n\n int currDiff = Math.abs(leftAvg - rightAvg);\n\n if (currDiff < minAvgDiff) {\n minAvgDiff = currDiff;\n ans = i;\n }\n }\n\n return ans;\n }\n}\n\n// TC: O(n ^ 2), SC: O(1)\n```\n##### 2. Using prefix-sum and suffix-sum arrays:\nWe precompute the prefix sums and suffix sums of each index of nums and sore them in separate arrays in order to save us from running nested loops.\n``` java []\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n int n = nums.length;\n long[] prefix = new long[n + 1];\n long[] suffix = new long[n + 1];\n\n for (int i = 0; i < n; i++) {\n prefix[i + 1] = prefix[i] + nums[i];\n }\n\n for (int i = n - 1; i >= 0; i--) {\n suffix[i] = suffix[i + 1] + nums[i];\n }\n\n int minAvgDiff = Integer.MAX_VALUE;\n int ans = -1;\n\n for (int i = 0; i < n; i++) {\n long leftAvg = prefix[i + 1] / (i + 1);\n long rightAvg = (i != n - 1)? suffix[i + 1] / (n - i - 1) : 0;\n\n int currDiff = (int) Math.abs(leftAvg - rightAvg);\n\n if (currDiff < minAvgDiff) {\n minAvgDiff = currDiff;\n ans = i;\n }\n }\n\n return ans;\n }\n}\n\n// TC: 3 * O(n) => O(n)\n// SC: 2 * O(n) => O(n)\n```\n##### 3. Without using extra space:\nWe precompute the total sum of every element of nums then run a loop to calculate left sum and left average. The right sum of that index will be given by subtracting the current sum at that index from the total sum and we can calculate the right average accordingly.\n``` java []\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n int n = nums.length;\n int ans = -1, minAvgDiff = Integer.MAX_VALUE;\n\n long totalSum = 0;\n for (int i : nums) totalSum += i;\n\n long currSum = 0;\n\n for (int i = 0; i < n; i++) {\n currSum += nums[i];\n\n long leftAvg = currSum / (i + 1);\n long rightAvg = (i != n - 1)? (totalSum - currSum) / (n - i - 1) : 0;\n\n int currDiff = (int) Math.abs(leftAvg - rightAvg);\n\n if (currDiff < minAvgDiff) {\n minAvgDiff = currDiff;\n ans = i;\n }\n }\n\n return ans;\n }\n}\n\n// TC: 2 * O(n) => O(n)\n// SC: O(1)\n```
2
0
['Prefix Sum', 'Java']
0
minimum-average-difference
C++ || O(N) || Easy to Understand with In-Depth Explanation
c-on-easy-to-understand-with-in-depth-ex-kpt5
Table of Contents\n\n- TL;DR\n - Code\n - Complexity\n- In Depth Analysis\n - Intuition\n - Approach\n - Example\n\n# TL;DR\n\n Precompute the total sum of
krazyhair
NORMAL
2022-12-04T16:20:42.890860+00:00
2023-01-05T06:20:14.294596+00:00
40
false
#### Table of Contents\n\n- [TL;DR](#tldr)\n - [Code](#code)\n - [Complexity](#complexity)\n- [In Depth Analysis](#in-depth-analysis)\n - [Intuition](#intuition)\n - [Approach](#approach)\n - [Example](#example)\n\n# TL;DR\n\n* Precompute the total sum of all the elements in the arrary\n* Iterate through `nums` and calculate the current average difference\n* If the current average difference is less than the lowest minimum so far, we update the answer and the lowest minimum\n\n## Code\n\n```c++\ntypedef long long ll;\n\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\n const int n = nums.size();\n\n ll total_sum = 0;\n for (int i = 0; i < n; i++)\n total_sum += nums[i];\n\n int minAvgDiff = INT_MAX, ans = 0, currAvgDiff;\n ll first_elements, last_elements, currSum = 0;\n for (int i = 0; i < n; i++) {\n currSum += nums[i];\n first_elements = currSum / (i + 1);\n last_elements = n - i - 1 != 0 ? (total_sum - currSum) / (n - i - 1) : 0;\n currAvgDiff = abs(first_elements - last_elements);\n if (currAvgDiff < minAvgDiff) {\n minAvgDiff = currAvgDiff;\n ans = i;\n }\n }\n\n return ans;\n }\n};\n```\n\n## Complexity\n\n**Time Complexity:** $$O(N)$$\n**Space Complexity:** $$O(1)$$\n\n**PLEASE UPVOTE IF YOU FIND MY POST HELPFUL!! \uD83E\uDD7A\uD83D\uDE01**\n\n---\n\n# In Depth Analysis\n\n## Intuition\n\nBy using the brute force approach, you must consistently calculate the sum of elements index $$0 \\rightarrow i$$ and index $$i+1 \\rightarrow n - 1$$. However, by precomputing the prefix sums of every element in O(n), we can calculate the average difference in O(1) time. \n\n**BUT**, we can make the space complexity even better by only computing the sum of all the elements opposed to the prefix sum\n\n## Approach \n\nFirst, we want to calculate the sum of all the elements in the array. Since the total could be greater than what could be stored in an integer, we are using a `long long` instead (type defined as `ll`)\n\nThen, we determine the average of the first `i` elements and last `n - i` elements for every `i` as we iterate. The only weird case is when `n - i - 1 == 0`, which means that the average of the last element is `0`\n\nThen, we just calculate what the current average difference is at index `i` and update the index `ans` and the current `minAvgDiff` if necessary. At the end, we just return the index\n\n## Example\n\nLets use the first example, where `nums = [2,5,3,9,5,3]`\n\n* Calculate total sum\n\nI won\'t actually go over this, but the total sum is 27\n\n* Iterate through Array\n\n| i | currSum | first | last | diff | minAvgDiff | ans |\n|:----:|:-------:|:--------------------:|:-----------------------------------------------:|------|:----------:|:---:|\n| Init | 0 | N/A | N/A | N/A | INT_MAX | 0 |\n| 0 | 2 | $$\\frac{2}{1} = 2$$ | $$\\frac{(27 - 2)}{(6 - 0 - 1)} = 5$$ | 3 | 3 | 0 |\n| 1 | 7 | $$\\frac{7}{2} = 3$$ | $$\\frac{(27 - 7)}{(6 - 1 - 1)} = 5$$ | 2 | 2 | 1 |\n| 2 | 10 | $$\\frac{10}{3} = 3$$ | $$\\frac{(27 - 10)}{(6 - 2 - 1)} = 5$$ | 2 | 2 | 1 |\n| 3 | 19 | $$\\frac{19}{4} = 4$$ | $$\\frac{(27 - 19)}{(6 - 3 - 1)} = 4$$ | 0 | 0 | 3 |\n| 4 | 24 | $$\\frac{24}{5} = 4$$ | $$\\frac{(27 - 24)}{(6 - 4 - 1)} = 3$$ | 1 | 0 | 3 |\n| 5 | 27 | $$\\frac{27}{6} = 4$$ | $$\\frac{(27 - 27)}{(6 - 5 - 1)} \\rightarrow 0$$ | 4 | 0 | 3 |\n\nAt the end, we just return `ans = 3` which is the correct answer\n\n**PLEASE UPVOTE IF YOU FIND MY POST HELPFUL!! \uD83E\uDD7A\uD83D\uDE01**
2
0
['Math', 'Prefix Sum', 'C++']
0
minimum-average-difference
C++ Solution
c-solution-by-pranto1209-75oi
Code\n\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\n int n = nums.size();\n vector<long long> pref(n+1), suf
pranto1209
NORMAL
2022-12-04T16:13:09.599933+00:00
2023-04-01T18:14:37.124551+00:00
27
false
# Code\n```\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\n int n = nums.size();\n vector<long long> pref(n+1), suff(n+1);\n for(int i=0; i<n; i++) pref[i+1] = pref[i] + nums[i];\n for(int i=n-1; i>=0; i--) suff[i] = suff[i+1] + nums[i];\n int ans;\n long long mn = INT_MAX;\n for(int i=1; i<=n; i++) {\n long long lt = pref[i], rt = suff[i];\n lt /= i;\n if(n - i) rt /= (n - i);\n if(abs(lt - rt) < mn) {\n mn = abs(lt - rt);\n ans = i-1;\n }\n } \n return ans;\n }\n};\n```
2
0
['C++']
0
minimum-average-difference
💡Python O(n) simple solution
python-on-simple-solution-by-space_invad-xkx3
Intuition\nAccording to constraint 1 <= nums.length <= 10 ** 5 we cannot re-calculate avg values for sub-arrays every time.\n\n# Approach\n\n1. Right handside a
space_invader
NORMAL
2022-12-04T14:04:01.757571+00:00
2022-12-04T14:21:10.685368+00:00
456
false
# Intuition\nAccording to constraint `1 <= nums.length <= 10 ** 5` we cannot re-calculate avg values for sub-arrays every time.\n\n# Approach\n\n1. Right handside area\n 1. Calculate a sum for all elements in `nums` for the further tracking\n 2. Remember `nums` len\n2. Left handside area\n 1. Set placeholders because we begin with the first index `0` we have nothing on the left area so it is `0` as well as the count of elements is `0`\n3. On each step of iteration we need to transfer numbers from the right area to the left area. We can do it by substituion the current number from the right area sum and adding it to the left area. Also we update the numbers of integers accordingly.\n\n# Complexity\n- Time complexity: O(n)\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n\n sum_right = sum(nums)\n len_right = len(nums)\n sum_left = 0\n len_left = 0\n\n min_avg = inf\n index = 0\n\n for i in range(len(nums)):\n \n sum_left += nums[i]\n len_left += 1\n\n sum_right -= nums[i]\n len_right -= 1\n\n #in case of only zeroes left on right\n if sum_right == 0:\n v = sum_left // len_left\n else:\n v = abs(\n sum_left // len_left - sum_right // len_right\n )\n\n if v < min_avg:\n min_avg = v\n index = i\n\n return index\n\n```
2
0
['Prefix Sum', 'Python3']
0
minimum-average-difference
Python || 91.23 % Faster || Prefix Sum || O(n) Solution
python-9123-faster-prefix-sum-on-solutio-s2um
\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n n=len(nums)\n pre,post=[nums[0]]*n,[nums[n-1]]*n\n for
pulkit_uppal
NORMAL
2022-12-04T11:50:28.027279+00:00
2022-12-04T11:50:28.027309+00:00
420
false
```\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n n=len(nums)\n pre,post=[nums[0]]*n,[nums[n-1]]*n\n for i in range(1,n):\n pre[i]=(nums[i]+pre[i-1])\n for i in range(n-2,-1,-1):\n post[i]=(nums[i]+post[i+1])\n m,f=1000000,n-1\n for i in range(n):\n x=pre[i]//(i+1)\n if i==n-1:\n y=0\n else:\n y=post[i+1]//(n-i-1)\n if m>abs(x-y):\n m=abs(x-y)\n f=i\n return f\n```\n\n**An upvote will be encouraging**
2
0
['Array', 'Prefix Sum', 'Python', 'Python3']
0
minimum-average-difference
Simple Java Solution with Time Complexity:O(N) && Space:O(1)
simple-java-solution-with-time-complexit-6uou
Hello Guys.....\n\tThis particular problem can be solved using O(N) complexity. To be more accurate, we need run time of O(2N) where N is the length of the arra
BhathrinaathanMB
NORMAL
2022-12-04T09:09:19.290419+00:00
2022-12-04T09:09:19.290458+00:00
52
false
***Hello Guys.....***\n\tThis particular problem can be solved using O(N) complexity. To be more accurate, we need run time of O(2N) where N is the length of the array. Firstly, we need to calculate the ***total sum*** of the array. We need a long variable since the sum could be large.\n\t\tSecondly we iterrate over the array once again and add each number to the **leftSum**. We find the **rightSum** using the **leftSum** and **totalSum**. Here is the java solution for the problem using the above approach.\n```\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n long sum=0,leftSum=0;\n int leftCount=1,rightCount=nums.length - 1;\n for (int i=0;i<nums.length;i++)\n sum+=nums[i];\n long lhs,rhs,min=999999999999999l;\n int index=0;\n for (int i=0;i<nums.length;i++)\n {\n leftSum+=nums[i];\n lhs=leftSum/leftCount;\n rhs=(rightCount>0)?(sum-leftSum)/rightCount:0;\n long avgDiff=((lhs-rhs)>0?lhs-rhs:rhs-lhs);\n if (i==0){min=avgDiff;}\n if (avgDiff<min)\n {\n min=avgDiff;\n index=i;\n }\n leftCount++;\n rightCount--;\n }\n return index; \n }\n}\n```\n\n\tWe can use the same approach, for solving similar problems such as [2270. Number of Ways to Split Array](http://leetcode.com/problems/number-of-ways-to-split-array/)\n\t\n***Happy Coding \nHave a nice day :)***\n\n
2
0
['Array', 'Prefix Sum']
0
minimum-average-difference
Easiest Solution using Prefix sum | Python
easiest-solution-using-prefix-sum-python-7ap9
Approach\nhttps://youtu.be/ykR8MsLAsWk\n\n# Code\n\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n prefix_sum = [0] *
sachinsingh31
NORMAL
2022-12-04T08:32:28.836777+00:00
2022-12-04T08:32:28.836820+00:00
113
false
# Approach\nhttps://youtu.be/ykR8MsLAsWk\n\n# Code\n```\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n prefix_sum = [0] * (len(nums) + 1)\n nums_len = len(nums)\n\n for index, element in enumerate(nums):\n prefix_sum[index+1] = prefix_sum[index] + element\n\n minimum_avg = float(inf)\n min_index = 0\n\n for index, element in enumerate(prefix_sum[1:]):\n right_sum = prefix_sum[-1] - element\n avg_diff = abs((element//(index+1)) - (right_sum // max(nums_len-index-1, 1)))\n\n if avg_diff < minimum_avg:\n minimum_avg = avg_diff\n min_index = index\n\n return min_index\n\n```
2
0
['Array', 'Prefix Sum', 'Python3']
0
minimum-average-difference
Java Simple Solution O(n) time complexity and O(1) space complexity
java-simple-solution-on-time-complexity-k67jd
\n# Code\n\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n int n=nums.length;\n long tsum=0;\n for(int i=0;i<n;i++)
raj-rkv
NORMAL
2022-12-04T08:01:04.694485+00:00
2022-12-04T08:01:04.694513+00:00
17
false
\n# Code\n```\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n int n=nums.length;\n long tsum=0;\n for(int i=0;i<n;i++)\n tsum+=nums[i];\n int ans=-1; //index of minimum average difference\n int mindif=Integer.MAX_VALUE; //value of minimum average difference\n long lsum=0;\n long rsum=0;\n for(int i=0;i<n;i++)\n {\n //count the no of elements of left and right respectively\n int lcount=i+1;\n int rcount=n-lcount;\n // left sum and right sum\n lsum+=nums[i];\n rsum=tsum-lsum;\n // Average of left and right\n long lavg=(lsum/lcount);\n long ravg=(rcount==0)?0:rsum/rcount;\n //Absolute difference\n int absdiff=(int)Math.abs(lavg-ravg);\n\n if(mindif>absdiff)\n {\n mindif=absdiff;\n ans=i;\n }\n\n\n\n \n \n }\n\n return ans;\n \n }\n}\n```
2
0
['Java']
0
minimum-average-difference
Easy CPP Solution Using Prefix Array | | Easy to Understand
easy-cpp-solution-using-prefix-array-eas-bemf
Intuition\n Describe your first thoughts on how to solve this problem. \n- We have to find the element whose average difference is lowest and if there are multi
ashishsutar1210
NORMAL
2022-12-04T06:44:55.671386+00:00
2022-12-04T06:45:50.743263+00:00
45
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- We have to find the element whose average difference is lowest and if there are multiple such elements then we have to return index of first such occuring element.\n- So, we can use Prefix Array for calculating average difference of all elements and then return the index of least average difference element.\n- We need to create the Prefix Array of long long int to avoid integer overflows.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. First we create a Prefix Array and then at every index we store the sum of elements till that index.\n2. Next at every index we store average difference (absolute difference of average of right elements and left elements) for the element at that index.\n3. As the last element has no right side element, it will store the average of all elements.\n4. Lastly we find the minimum element from the array of average difference .\n5. After iterating in array we find the minimum element and return its index.\n Hope You Understand!\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ For Prefix Array\n\n# Code\n```\nclass Solution {\npublic:\n int minimumAverageDifference(vector<int>& nums) {\n\n // Using Prefix Array\n\n vector<long long int>arr(nums.size(),0);\n arr[0]=nums[0];\n for(int i=1;i<nums.size();i++)\n {\n arr[i] += arr[i-1] + nums[i]; // Created a prefix array\n }\n for(int i=0;i<nums.size()-1;i++)\n {\n arr[i] = arr[i]/(i+1) - ((arr[nums.size()-1] - arr[i])/(nums.size()-i-1)); // To store the difference of average at that index\n\n arr[i] = abs(arr[i]);\n }\n\n arr[nums.size()-1] /= nums.size(); //Last index will have no elements on right side so it will store average of all.\n\n long long int &temp = *min_element(arr.begin(),arr.end());// to find the smallest element in array with least average difference.\n\n for(int i=0;i<nums.size();i++)\n {\n if(arr[i]==temp)return i;//returning index of smallest element.\n }\n return 0;\n }\n};\n```
2
0
['Array', 'Prefix Sum', 'C++']
1
minimum-average-difference
Easy
easy-by-cnbak-urlr
long long int n=nums.size();\n long long int presum[n];\n presum[0]=nums[0];\n for(int i=1;i=0;i--)\n {\n sufsum[i]=sufsu
CNBAK
NORMAL
2022-12-04T06:21:52.096414+00:00
2022-12-04T06:21:52.096455+00:00
226
false
long long int n=nums.size();\n long long int presum[n];\n presum[0]=nums[0];\n for(int i=1;i<n;i++)\n {\n presum[i]=presum[i-1]+nums[i];\n }\n \n long long sufsum[n];\n sufsum[n-1]=nums[n-1];\n for(int i=n-2;i>=0;i--)\n {\n sufsum[i]=sufsum[i+1]+nums[i];\n }\n \n long long mini=INT_MAX;\n long long int ans=0;\n for(int i=0;i<n;i++)\n {\n long long int x,y;\n if(i==n-1)\n {\n \n \n x=presum[i]/(i+1);\n \n y=0;\n\n }\n else\n {\n \n x=presum[i]/(i+1);\n \n y=sufsum[i+1]/(n-i-1);\n \n }\n \n \n \n if(abs(x-y)<mini)\n {\n mini=abs(x-y);\n ans=i;\n }\n }\n \n \n return ans;
2
0
['C', 'Prefix Sum']
2
minimum-average-difference
[Java] ✅ Runtime: 12ms, faster than 100.00% | O(N) time, O(1) space🔥🔥🔥
java-runtime-12ms-faster-than-10000-on-t-oo7c
java\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n int n = nums.length;\n\t\t\n\t\tlong sum = 0;\n for(int num : nums
Suvradippaul
NORMAL
2022-12-04T05:20:02.916944+00:00
2022-12-04T05:45:13.817952+00:00
259
false
```java\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n int n = nums.length;\n\t\t\n\t\tlong sum = 0;\n for(int num : nums) sum += num;\n\t\t\n long minDiff = Integer.MAX_VALUE;\n\t\tlong leftSum = 0; long rightSum = sum;\n int ans = 0;\n \n for (int i = 0; i < n; i++) {\n leftSum += nums[i];\n rightSum -= nums[i];\n long lAvg = leftSum/(i+1);\n long rAvg = (n-1-i) != 0 ? rightSum/(n-1-i) : rightSum;\n long diff = Math.abs(lAvg - rAvg);\n if (diff == 0) return i;\n if (diff < minDiff) {\n minDiff = diff;\n ans = i;\n }\n }\n \n return ans;\n }\n}\n```
2
0
['Java']
0
minimum-average-difference
✅ C++ Simple | Prefix Sum | O(n)
c-simple-prefix-sum-on-by-nitink_33-fc6n
\nclass Solution {\npublic:\n \n int minimumAverageDifference(vector<int>& nums) \n { \n int ans_idx=0;\n int n=nums.size();\n
HustlerNitin
NORMAL
2022-12-04T04:57:43.679164+00:00
2022-12-04T04:57:43.679189+00:00
258
false
```\nclass Solution {\npublic:\n \n int minimumAverageDifference(vector<int>& nums) \n { \n int ans_idx=0;\n int n=nums.size();\n if(n==1) return 0;\n \n long long ans = INT_MAX, sum = 0;\n \n for(int i=0;i<n;i++)\n sum += nums[i];\n // prefix sum\n vector<long long>pre(n);\n \n pre[0] = nums[0];\n for(int i=1;i<n;i++)\n pre[i] = nums[i] + pre[i-1];\n \n for(int i=0;i<nums.size();i++)\n { \n long long firstSum = pre[i];\n long long lastSum = (sum - pre[i]);\n long long diff=0;\n \n if((n-i-1)!= 0)\n diff = abs(firstSum/(i+1) - lastSum/(n-i-1));\n else\n diff = firstSum/(i+1) - 0;\n \n if(diff < ans)\n {\n ans = diff;\n ans_idx = i;\n }\n }\n return ans_idx;\n }\n};\n```\n***Thanks for Upvoting !***\n\uD83D\uDE42
2
0
['Array', 'C', 'Prefix Sum', 'C++']
0
minimum-average-difference
Easy C++
easy-c-by-niraj03-kq92
\n# Approach\nBy checking average upto index\n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity: O(n)\n Add your time complexi
Niraj03
NORMAL
2022-12-04T04:16:13.400792+00:00
2022-12-04T04:16:13.400881+00:00
25
false
\n# Approach\nBy checking average upto index\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\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 minimumAverageDifference(vector<int>& nums) {\n long long minAv = INT_MAX;\n int idx = 0;\n long long sSum = 0, eSum = accumulate(nums.begin(),nums.end(),(long long)0);\n long long p=0,q=nums.size();\n for(int i=0;i<nums.size();i++){\n sSum += nums[i];\n eSum -= nums[i];\n p++, q--;\n long long av1 = sSum / p;\n long long av2;\n if(q==0)\n av2 = 0;\n else\n av2 = eSum / q;;\n if(abs(av1-av2) < minAv){\n minAv = abs(av1-av2);\n idx = i;\n }\n }\n return idx;\n }\n};\n```
2
0
['C++']
0
minimum-average-difference
C# | Linear Approach
c-linear-approach-by-c_4less-kvyb
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nPointer technique\n\n#
c_4less
NORMAL
2022-12-04T03:07:08.908011+00:00
2022-12-04T03:07:08.908044+00:00
98
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nPointer technique\n\n# Complexity\n- Time complexity: O(n)\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```\npublic class Solution {\n public int MinimumAverageDifference(int[] nums) {\n long leftSum = 0;\n long rightSum = nums.Sum(n => (long)n);\n\n int leftDivisor = 0;\n int rightDivisor = nums.Length;\n long bestAvg =Int32.MaxValue;\n int bestAvgIdx =0;\n \n\n for(int i=0; i< nums.Length; i++)\n {\n leftSum += nums[i];\n rightSum -= nums[i];\n\n leftDivisor +=1;\n rightDivisor = rightDivisor-1 == 0 ? 1: rightDivisor-1;\n\n int bestScore = (int)Math.Abs(leftSum / leftDivisor - rightSum / rightDivisor);\n\n if (bestScore < bestAvg)\n {\n bestAvgIdx = i;\n bestAvg = bestScore;\n }\n }\n return bestAvgIdx;\n }\n}\n```
2
0
['C#']
1
minimum-average-difference
Straightforward and Detailed Solution O(n)
straightforward-and-detailed-solution-on-islj
Approach\n Describe your approach to solving the problem. \nCreate a prefix sum array. Then iterate through the prefix sum array to obtain the averages. Then w
HaiderKhan1
NORMAL
2022-12-04T02:14:48.349110+00:00
2022-12-04T02:14:48.349143+00:00
179
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nCreate a prefix sum array. Then iterate through the prefix sum array to obtain the averages. Then we simply check if this average is the minAvg so far. I have outlined an equation which can be used to solve this.\n# Complexity\n- Time complexity: O(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```\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n \n # pesudo code:\n\n # prefix sum array\n # [2, 7, 10, 19, 24, 27]\n\n # n = 6\n # i = 0\n # equation: |(num[i] // i+1) - (nums[n-1] - nums[i] / n - i + 1)|\n # |2 - ((27 - 2) / 5)|\n # |2 - 5| \n # 3\n\n # (7 // 2) \n\n n = len(nums)\n prefix = [nums[0]]\n minDiff = float("inf")\n idx = 0\n\n # compute the prefix sum of the array\n for i in range(1, n):\n prefix.append(prefix[-1] + nums[i])\n \n # find the min difference average\n for i in range(n):\n \n first = prefix[i] // (i+1)\n second = 0\n\n if (n - i - 1) > 0:\n second = (prefix[n-1] - prefix[i]) // (n - i - 1)\n\n avg = abs(first - second)\n \n if avg < minDiff:\n idx = i\n minDiff = avg\n \n return idx\n\n```
2
0
['Math', 'Prefix Sum', 'Python3']
1
minimum-average-difference
Simple Python Solution
simple-python-solution-by-arjun_d-sfa2
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
arjun_d
NORMAL
2022-12-04T01:29:51.794295+00:00
2022-12-04T02:18:33.411840+00:00
275
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)\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(object):\n def minimumAverageDifference(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n end = 0\n front = 0\n mindif = 100000000000\n location = 0\n\n for x in nums:\n end += x\n\n for x in range(len(nums)):\n front += nums[x]\n end -= nums[x]\n if x == len(nums) - 1:\n currdif = front/len(nums)\n else:\n currdif = abs((front/(x+1)) - (end/(len(nums)-(x+1))))\n if currdif < mindif:\n mindif = currdif\n location = x \n \n return location\n```
2
0
['Python']
1
minimum-average-difference
Java || Easy Solution || Datatype Manipulation ✨
java-easy-solution-datatype-manipulation-p9kw
4 Test cases not passing just for Integer underflow --> \n\n\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n int n = nums.leng
Ritabrata_1080
NORMAL
2022-10-02T12:00:39.268068+00:00
2022-10-02T15:38:44.666876+00:00
159
false
# 4 Test cases not passing just for Integer underflow --> \n\n```\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n int n = nums.length;\n List<Integer> list = new ArrayList<>();\n int res[] = new int[n];\n int pref = 0;\n int suf = 0;\n for(int i = 0;i<n;i++){\n suf += nums[i];\n }\n for(int i = 0;i<n-1;i++){\n pref += nums[i];\n suf -= nums[i];\n int lem = pref/(i+1);\n int sem = suf/(n-i-1);\n res[i] = Math.abs(lem - sem);\n }\n int freshSum = 0;\n for(int p : nums){\n freshSum += p;\n }\n res[n-1] = Math.abs(freshSum/n);\n int min = Integer.MAX_VALUE;\n int result = -1;\n for(int p : res){\n if(p < min){\n min = p;\n }\n }\n for(int i = 0;i<n;i++){\n if(res[i] == min){\n list.add(i);\n }\n }\n Collections.sort(list);\n return list.get(0);\n }\n}\n```\n\n# Revised code with long datatype-->\n```\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n int n = nums.length;\n List<Integer> list = new ArrayList<>();\n long res[] = new long[n];\n long pref = 0;\n long suf = 0;\n for(int i = 0;i<n;i++){\n suf += nums[i];\n }\n for(int i = 0;i<n-1;i++){\n pref += nums[i];\n suf -= nums[i];\n long lem = pref/(i+1);\n long sem = suf/(n-i-1);\n res[i] = Math.abs(lem - sem);\n }\n long freshSum = 0;\n for(long p : nums){\n freshSum += p;\n }\n res[n-1] = Math.abs(freshSum/n);\n long min = Long.MAX_VALUE;\n int result = -1;\n for(long p : res){\n if(p < min){\n min = p;\n }\n }\n for(int i = 0;i<n;i++){\n if(res[i] == min){\n result = i;\n break;\n }\n }\n return result;\n }\n}\n```
2
0
['Prefix Sum', 'Java']
0