#include<iostream> #include<vector> using namespace std; int MaxSubArraySum_1(const vector<int> &arr){ int n=arr.size(); if(n==0) return 0; int sum=arr[0]; int max=arr[0]; for(int i=1;i<n;i++){ if(sum>=0) sum+=arr[i]; else sum=arr[i]; if(sum>max) max=sum; } return max; } int MaxSubArraySum_2(const vector<int> &arr){ int n=arr.size(); if(n==0) return 0; vector<int> maxSub(n); maxSub[0]=arr[0]; int max=arr[0]; for(int i=1;i<n;i++){ maxSub[i]=(maxSub[i-1]>0)?(maxSub[i-1]+arr[i]):arr[i]; if(max<maxSub[i]) max=maxSub[i]; } return max; } int MaxSubMatrixSum(const vector<vector<int> > &arr){ int m=arr.size(); int n=arr[0].size(); vector<vector<int> > total(m,vector<int>(n,0)); for(int i=0;i<n;i++) total[0][i]=arr[0][i]; for(int i=1;i<m;i++){ for(int j=0;j<n;j++){ total[i][j]=total[i-1][j]+arr[i][j]; } } int max=-1000; vector<int> result(n); for(int i=0;i<m;i++){ for(int j=i;j<m;j++){ for(int f=0;f<n;f++){ if(i==0) result[f]=total[j][f]; else result[f]=total[j][f]-total[i-1][f]; } int maximal=MaxSubArraySum_2(result); if(maximal>max) max=maximal; } } return max; } int main(){ vector<vector<int> > mat={{0,-2,-7,0},{9,2,-6,2},{-4,1,-4,1},{-1,8,0,-2}}; cout<< MaxSubMatrixSum(mat); return 0; }