please help in writing code for prefix sum
explain logic for the prefix sum part in 2d matrix
Doubt in a small part of the explaination
hi @rsumitaj
as explain in video
first you have o calculate prefix sum matrix
for(int i=0;i<n;i++){
for(int j=1;i<m;i++){
sum[i][j]=arr[i][j]+arr[i][j-1];
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
sum[i][j]=sum[i][j]+sum[i-1][j];
}
}
and then using 4 for loops find 4 cordinate of rectangle and using prefix sum calculate ans;
for(int tli=0;tli<n;tli++){
for(int tlj=0;tlj<m;tlj++){
for(int bri=tli;bri<n;bri++){
for(int brj=tlj;brj<m;brj++){
/// now you have 4 cordinates
/// and you can find sum of these submatrix easly
int ans=sum[bri][brj];
if((tli-1>=0)&&(tlj-1>=0))ans+=sum[tli-1][tlj-1];
if(tli-1>=0)ans-=sum[tli-1][brj];
if(tlj-1>=0)ans-=sum[bri][tlj-1];
finalans+=ans;
}
}
}
}