calculating max sum of a sub rectangle in an array

given a 2d array, how can we calculate the maximum answer that any of its subRECTANGLE could give when that subrectangle's elements are summed up.
i came up with this solution...but it seems to have some problem as the array that i am giving to it should give me the answer of 15 but i am getting 2.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
using namespace std;

int main()
{
        int max=0;
        int sum=0;
        int arr[4][4]={0,-2,-7,0,9,2,-6,2,-4,1,-4,1,-1,8,0,-2};
        for(int i=0; i<4; i++)
        {
                for(int j=i; j<4; j++)
                {
                        sum=arr[i][j];
                        for(int k=i+1; k<4; k++)
                        {
                                for(int l=k; l<4; l++)
                                {
                                        sum += arr[k][l];
                                        if(sum>max)
                                        {
                                                max=sum;
                                        }
                                }
                        }
                }
        }
        cout<<"The max sum is: "<<max<<endl;
        return 0;
}

can someone figure out the problem or give a more efficient code.
Last edited on
Topic archived. No new replies allowed.