The output of this code should be 3400 but form implementation of this method the output comes out to be 1832

#include<bits/stdc++.h>
using namespace std;

int main(){
int a[4][4];

int val=1;
for(int i=0;i<4;i++)
    for(int j=0;j<4;j++)
        {
            a[i][j]=val;
            val++;
        }
int csum[4][4]={0};//prefix array row wise
for(int i=1;i<4;i++)
    for(int j=0;j<4;j++)
       a[i][j]+=a[i-1][j];

for(int i=0;i<4;i++)//prefix array column wise
    for(int j=1;j<4;j++)
        a[i][j]+=a[i][j-1];
int n=4; 
int sum=0;
for(int li=0;li<n;li++)//top left i
    for(int lj=0;lj<n;lj++)//top left j
        for(int bi=li;bi<n;bi++)// bottom right i
            for(int bj=lj;bj<n;bj++)//bottom right j
                sum+=a[bi][bj]-a[li-1][bj]-a[bi][lj-1]+a[li-1][lj-1];
cout<<sum;

}

hi @iamlovelesh

for(int li=0;li<n;li++)//top left i
    for(int lj=0;lj<n;lj++)//top left j
        for(int bi=li;bi<n;bi++)// bottom right i
            for(int bj=lj;bj<n;bj++)//bottom right j
               {
                   sum+=a[bi][bj];
                    if(lj>0)sum-=a[bi][lj-1];
                    if(li>0)sum-=a[li-1][bj];
                    if(li>0&&lj>0)sum+=a[li-1][lj-1];
               }

this is modified code
only error is you have not check condition
if(li==0) you get negative index due to which garbage is add or subtract from sum and
hence you got wrong ans;

i hope this help
if you have more doubts regarding feel free to ask
if your doubt is resolved mark it as resolved from your doubt section inside your course

1 Like