Maximum Subarray and (Dynamic Programming)

Topic Description
There is a two-dimensional array of positive and negative numbers. A submatrix is a subarray in which any adjacent subscript is 1*1 or larger. The sum of a submatrix is the sum of all elements in the submatrix. In this problem, the submatrix with the largest sum is called the largest submatrix.
For example:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
The maximum submatrix of this array is:
9 2
-4 1
-1 8
The sum is 15.
input
The input contains multiple sets of test data. The first line of each set of inputs is a positive integer N (1<=N<=100), representing the size of a two-dimensional square matrix. Next, N lines input N integers per line, representing array elements, ranging from [-127, 127].
output
Output maximum subarray sum.
sample input

4
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2

sample output

15

Analysis:
If a one-dimensional array finds the largest subarray, then it finds a sum of the largest ascending subsequences.
Therefore, two-dimensional arrays can be compressed into one-dimensional arrays, i. e. the addition of rows.

Code implementation:

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int maxs(int *w,int n)
{
    int m[110];
    int maxn;
    maxn=w[0];
    m[0]=w[0];
    int i;
    for(i=1;i<n;i++)
    {
        if(m[i-1]>0)
            m[i]=m[i-1]+w[i];
        else
            m[i]=w[i];
        if(maxn<m[i])
            maxn=m[i];
    }
    return maxn;
}
int main()
{
int a[110][110];
int b[110][110];
int q[110];
    int n,i,j,k;
    while(cin>>n)
    {
        for(i=0; i<n; i++)
            for(j=0; j<n; j++)
            {
                cin>>a[i][j];
                b[i][j]=a[i][j];
            }
        for(i=1; i<n; i++)
            for(j=0; j<n; j++)
                b[i][j]+=b[i-1][j];
        int maxn=-999;


        for(i=0; i<n; i++)
        {
            for(j=i; j<n; j++)
            {
                for(k=0; k<n; k++)
                    if(i==0)
                        q[k]=b[j][k];
                    else
                        q[k]=b[j][k]-b[i-1][k];
                int result=maxs(q,n);
                maxn=max(result,maxn);
            }
        }


        cout<<maxn<<endl;
    }
    return 0;
}

Posted by lordvader on Tue, 30 Jul 2019 15:28:57 -0700