📜  最大总和子矩阵

📅  最后修改于: 2021-04-17 16:31:12             🧑  作者: Mango

先决条件: Kadane算法

给定尺寸为N * M的二维数组arr [] [] ,任务是从矩阵arr [] []中找到最大和子矩阵。

例子:

天真的方法:最简单的方法是从给定的矩阵生成所有可能的子矩阵,然后计算它们的总和。最后,打印获得的最大金额。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find maximum sum submatrix
void maxSubmatrixSum(
    vector > matrix)
{
    // Stores the number of rows
    // and columns in the matrix
    int r = matrix.size();
    int c = matrix[0].size();
 
    // Stores maximum submatrix sum
    int maxSubmatrix = 0;
 
    // Take each row as starting row
    for (int i = 0; i < r; i++) {
 
        // Take each column as the
        // starting column
        for (int j = 0; j < c; j++) {
 
            // Take each row as the
            // ending row
            for (int k = i; k < r; k++) {
 
                // Take each column as
                // the ending column
                for (int l = j; l < c; l++) {
 
                    // Stores the sum of submatrix
                    // having topleft index(i, j)
                    // and bottom right index (k, l)
                    int sumSubmatrix = 0;
 
                    // Iterate the submatrix
                    // row-wise and calculate its sum
                    for (int m = i; m <= k; m++) {
                        for (int n = j; n <= l; n++) {
                            sumSubmatrix += matrix[m][n];
                        }
                    }
 
                    // Update the maximum sum
                    maxSubmatrix
                        = max(maxSubmatrix,
                              sumSubmatrix);
                }
            }
        }
    }
 
    // Print the answer
    cout << maxSubmatrix;
}
 
// Driver Code
int main()
{
    vector > matrix = { { 0, -2, -7, 0 },
                                    { 9, 2, -6, 2 },
                                    { -4, 1, -4, 1 },
                                    { -1, 8, 0, -2 } };
 
    maxSubmatrixSum(matrix);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG
{
 
// Function to find maximum sum submatrix
static void maxSubmatrixSum(int[][] matrix)
{
   
    // Stores the number of rows
    // and columns in the matrix
    int r = matrix.length;
    int c = matrix[0].length;
 
    // Stores maximum submatrix sum
    int maxSubmatrix = 0;
 
    // Take each row as starting row
    for (int i = 0; i < r; i++) {
 
        // Take each column as the
        // starting column
        for (int j = 0; j < c; j++) {
 
            // Take each row as the
            // ending row
            for (int k = i; k < r; k++) {
 
                // Take each column as
                // the ending column
                for (int l = j; l < c; l++) {
 
                    // Stores the sum of submatrix
                    // having topleft index(i, j)
                    // and bottom right index (k, l)
                    int sumSubmatrix = 0;
 
                    // Iterate the submatrix
                    // row-wise and calculate its sum
                    for (int m = i; m <= k; m++) {
                        for (int n = j; n <= l; n++) {
                            sumSubmatrix += matrix[m][n];
                        }
                    }
 
                    // Update the maximum sum
                    maxSubmatrix
                        = Math.max(maxSubmatrix,
                              sumSubmatrix);
                }
            }
        }
    }
 
    // Print the answer
    System.out.println(maxSubmatrix);
}
   
// Driver Code
public static void main(String[] args)
{
    int[][] matrix = { { 0, -2, -7, 0 },
                        { 9, 2, -6, 2 },
                        { -4, 1, -4, 1 },
                        { -1, 8, 0, -2 } };
 
    maxSubmatrixSum(matrix);
}
}
 
// This code is contributed by susmitakundugoaldanga.


Python3
# Python3 program for the above approach
 
# Function to find maximum sum submatrix
def maxSubmatrixSum(matrix):
   
    # Stores the number of rows
    # and columns in the matrix
    r = len(matrix)
    c = len(matrix[0])
 
    # Stores maximum submatrix sum
    maxSubmatrix = 0
 
    # Take each row as starting row
    for i in range(r):
 
        # Take each column as the
        # starting column
        for j in range(c):
 
            # Take each row as the
            # ending row
            for k in range(i, r):
 
                # Take each column as
                # the ending column
                for l in range(j, c):
 
                    # Stores the sum of submatrix
                    # having topleft index(i, j)
                    # and bottom right index (k, l)
                    sumSubmatrix = 0
 
                    # Iterate the submatrix
                    # row-wise and calculate its sum
                    for m in range(i, k + 1):
                        for n in range(j, l + 1):
                            sumSubmatrix += matrix[m][n]
 
                    # Update the maximum sum
                    maxSubmatrix= max(maxSubmatrix, sumSubmatrix)
 
    # Prthe answer
    print (maxSubmatrix)
 
# Driver Code
if __name__ == '__main__':
    matrix = [ [ 0, -2, -7, 0 ],
                [ 9, 2, -6, 2 ],
                [ -4, 1, -4, 1 ],
                [ -1, 8, 0, -2 ] ]
 
    maxSubmatrixSum(matrix)
 
    # This code is contributed by mohit kumar 29.


C#
// C# program to implement
// the above approach
using System;
public class GFG
{
// Function to find maximum sum submatrix
static void maxSubmatrixSum(int[,] matrix)
{
   
    // Stores the number of rows
    // and columns in the matrix
    int r = matrix.GetLength(0);
    int c = matrix.GetLength(1);
 
    // Stores maximum submatrix sum
    int maxSubmatrix = 0;
 
    // Take each row as starting row
    for (int i = 0; i < r; i++) {
 
        // Take each column as the
        // starting column
        for (int j = 0; j < c; j++) {
 
            // Take each row as the
            // ending row
            for (int k = i; k < r; k++) {
 
                // Take each column as
                // the ending column
                for (int l = j; l < c; l++) {
 
                    // Stores the sum of submatrix
                    // having topleft index(i, j)
                    // and bottom right index (k, l)
                    int sumSubmatrix = 0;
 
                    // Iterate the submatrix
                    // row-wise and calculate its sum
                    for (int m = i; m <= k; m++) {
                        for (int n = j; n <= l; n++) {
                            sumSubmatrix += matrix[m, n];
                        }
                    }
 
                    // Update the maximum sum
                    maxSubmatrix
                        = Math.Max(maxSubmatrix,
                              sumSubmatrix);
                }
            }
        }
    }
 
    // Print the answer
    Console.WriteLine(maxSubmatrix);
}
 
// Driver Code
public static void Main(String []args)
{
    int[,] matrix = { { 0, -2, -7, 0 },
                        { 9, 2, -6, 2 },
                        { -4, 1, -4, 1 },
                        { -1, 8, 0, -2 } };
 
    maxSubmatrixSum(matrix);
}
}
 
// This code is contributed by sanjoy_62.


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find maximum continuous
// maximum sum in the array
int kadane(vector v)
{
   
    // Stores current and maximum sum
    int currSum = 0;
    int maxSum = INT_MIN;
 
    // Traverse the array v
    for (int i = 0;
         i < (int)v.size(); i++) {
 
        // Add the value of the
        // current element
        currSum += v[i];
 
        // Update the maximum sum
        if (currSum > maxSum) {
            maxSum = currSum;
        }
 
        if (currSum < 0) {
            currSum = 0;
        }
    }
 
    // Return the maximum sum
    return maxSum;
}
 
// Function to find the maximum
// submatrix sum
void maxSubmatrixSum(
    vector > A)
{
   
    // Store the rows and columns
    // of the matrix
    int r = A.size();
    int c = A[0].size();
 
    // Create an auxiliary matrix
    int** prefix = new int*[r];
 
    // Traverse the matrix, prefix
    // and initialize it will all 0s
    for (int i = 0; i < r; i++) {
 
        prefix[i] = new int;
        for (int j = 0; j < c; j++) {
            prefix[i][j] = 0;
        }
    }
 
    // Calculate prefix sum of all
    // rows of matrix A[][] and
    // store in matrix prefix[]
    for (int i = 0; i < r; i++) {
 
        for (int j = 0; j < c; j++) {
 
            // Update the prefix[][]
            if (j == 0)
                prefix[i][j] = A[i][j];
            else
                prefix[i][j] = A[i][j]
                               + prefix[i][j - 1];
        }
    }
 
    // Store the maximum submatrix sum
    int maxSum = INT_MIN;
 
    // Iterate for starting column
    for (int i = 0; i < c; i++) {
 
        // Iterate for last column
        for (int j = i; j < c; j++) {
 
            // To store current array
            // elements
            vector v;
 
            // Traverse every row
            for (int k = 0; k < r; k++) {
 
                // Store the sum of the
                // kth row
                int el = 0;
 
                // Update the prefix
                // sum
                if (i == 0)
                    el = prefix[k][j];
                else
                    el = prefix[k][j]
                         - prefix[k][i - 1];
 
                // Push it in a vector
                v.push_back(el);
            }
 
            // Update the maximum
            // overall sum
            maxSum = max(maxSum, kadane(v));
        }
    }
 
    // Print the answer
    cout << maxSum << "\n";
}
 
// Driver Code
int main()
{
    vector > matrix = { { 0, -2, -7, 0 },
                                    { 9, 2, -6, 2 },
                                    { -4, 1, -4, 1 },
                                    { -1, 8, 0, -2 } };
 
    // Function Call
    maxSubmatrixSum(matrix);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG{
 
  // Function to find maximum continuous
  // maximum sum in the array
  static int kadane(Vector v)
  {
 
    // Stores current and maximum sum
    int currSum = 0;
    int maxSum = Integer.MIN_VALUE;
 
    // Traverse the array v
    for (int i = 0;
         i < (int)v.size(); i++)
    {
 
      // Add the value of the
      // current element
      currSum += v.get(i);
 
      // Update the maximum sum
      if (currSum > maxSum)
      {
        maxSum = currSum;
      }
 
      if (currSum < 0)
      {
        currSum = 0;
      }
    }
 
    // Return the maximum sum
    return maxSum;
  }
 
  // Function to find the maximum
  // submatrix sum
  static void maxSubmatrixSum(int [][]A)
  {
    // Store the rows and columns
    // of the matrix
    int r = A.length;
    int c = A[0].length;
 
    // Create an auxiliary matrix
    int [][]prefix = new int[r][];
 
    // Traverse the matrix, prefix
    // and initialize it will all 0s
    for (int i = 0; i < r; i++) {
 
      prefix[i] = new int;
      for (int j = 0; j < c; j++) {
        prefix[i][j] = 0;
      }
    }
 
    // Calculate prefix sum of all
    // rows of matrix A[][] and
    // store in matrix prefix[]
    for (int i = 0; i < r; i++) {
 
      for (int j = 0; j < c; j++) {
 
        // Update the prefix[][]
        if (j == 0)
          prefix[i][j] = A[i][j];
        else
          prefix[i][j] = A[i][j]
          + prefix[i][j - 1];
      }
    }
 
    // Store the maximum submatrix sum
    int maxSum = Integer.MIN_VALUE;
 
    // Iterate for starting column
    for (int i = 0; i < c; i++) {
 
      // Iterate for last column
      for (int j = i; j < c; j++) {
 
        // To store current array
        // elements
        Vector v = new Vector();
 
        // Traverse every row
        for (int k = 0; k < r; k++) {
 
          // Store the sum of the
          // kth row
          int el = 0;
 
          // Update the prefix
          // sum
          if (i == 0)
            el = prefix[k][j];
          else
            el = prefix[k][j]
            - prefix[k][i - 1];
 
          // Push it in a vector
          v.add(el);
        }
 
        // Update the maximum
        // overall sum
        maxSum = Math.max(maxSum, kadane(v));
      }
    }
 
    // Print the answer
    System.out.print(maxSum+ "\n");
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int [][]matrix = { { 0, -2, -7, 0 },
                      { 9, 2, -6, 2 },
                      { -4, 1, -4, 1 },
                      { -1, 8, 0, -2 } };
 
    // Function Call
    maxSubmatrixSum(matrix);
  }
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach
import sys
 
# Function to find maximum continuous
# maximum sum in the array
def kadane(v):
     
    # Stores current and maximum sum
    currSum = 0
     
    maxSum = -sys.maxsize - 1
     
    # Traverse the array v
    for i in range(len(v)):
         
        # Add the value of the
        # current element
        currSum += v[i]
         
        # Update the maximum sum
        if (currSum > maxSum):
            maxSum = currSum
        if (currSum < 0):
            currSum = 0
     
    # Return the maximum sum
    return maxSum
 
# Function to find the maximum
# submatrix sum
def maxSubmatrixSum(A):
     
    # Store the rows and columns
    # of the matrix
    r = len(A)
    c = len(A[0])
     
    # Create an auxiliary matrix
    # Traverse the matrix, prefix
    # and initialize it will all 0s
    prefix = [[0 for i in range(c)]
                 for j in range(r)]
     
    # Calculate prefix sum of all
    # rows of matrix A[][] and
    # store in matrix prefix[]
    for i in range(r):
        for j in range(c):
             
            # Update the prefix[][]
            if (j == 0):
                prefix[i][j] = A[i][j]
            else:
                prefix[i][j] = A[i][j] + prefix[i][j - 1]
     
    # Store the maximum submatrix sum
    maxSum = -sys.maxsize - 1
     
    #  Iterate for starting column
    for i in range(c):
         
        # Iterate for last column
        for j in range(i, c):
             
            # To store current array
            # elements
            v = []
             
            # Traverse every row
            for k in range(r):
                 
                # Store the sum of the
                # kth row
                el = 0
                 
                # Update the prefix
                # sum
                if (i == 0):
                    el = prefix[k][j]
                else:
                    el = prefix[k][j] - prefix[k][i - 1]
                 
                # Push it in a vector
                v.append(el)
             
            # Update the maximum
            # overall sum
            maxSum = max(maxSum, kadane(v))
     
    # Print the answer
    print(maxSum)
 
# Driver Code
matrix = [ [ 0, -2, -7, 0 ],
           [ 9, 2, -6, 2 ],
           [ -4, 1, -4, 1 ],
           [ -1, 8, 0, -2 ] ]
            
# Function Call
maxSubmatrixSum(matrix)
 
# This code is contributed by rag2127


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG{
 
  // Function to find maximum continuous
  // maximum sum in the array
  static int kadane(List v)
  {
 
    // Stores current and maximum sum
    int currSum = 0;
    int maxSum = int.MinValue;
 
    // Traverse the array v
    for (int i = 0;
         i < (int)v.Count; i++)
    {
 
      // Add the value of the
      // current element
      currSum += v[i];
 
      // Update the maximum sum
      if (currSum > maxSum)
      {
        maxSum = currSum;
      }
 
      if (currSum < 0)
      {
        currSum = 0;
      }
    }
 
    // Return the maximum sum
    return maxSum;
  }
 
  // Function to find the maximum
  // submatrix sum
  static void maxSubmatrixSum(int [,]A)
  {
    // Store the rows and columns
    // of the matrix
    int r = A.GetLength(0);
    int c = A.GetLength(1);
 
    // Create an auxiliary matrix
    int [,]prefix = new int[r,c];
 
    // Traverse the matrix, prefix
    // and initialize it will all 0s
    for (int i = 0; i < r; i++) {
      for (int j = 0; j < c; j++) {
        prefix[i,j] = 0;
      }
    }
 
    // Calculate prefix sum of all
    // rows of matrix [,]A and
    // store in matrix prefix[]
    for (int i = 0; i < r; i++) {
 
      for (int j = 0; j < c; j++) {
 
        // Update the prefix[,]
        if (j == 0)
          prefix[i,j] = A[i,j];
        else
          prefix[i,j] = A[i,j]
          + prefix[i,j - 1];
      }
    }
 
    // Store the maximum submatrix sum
    int maxSum = int.MinValue;
 
    // Iterate for starting column
    for (int i = 0; i < c; i++) {
 
      // Iterate for last column
      for (int j = i; j < c; j++) {
 
        // To store current array
        // elements
        List v = new List();
 
        // Traverse every row
        for (int k = 0; k < r; k++) {
 
          // Store the sum of the
          // kth row
          int el = 0;
 
          // Update the prefix
          // sum
          if (i == 0)
            el = prefix[k,j];
          else
            el = prefix[k,j]
            - prefix[k,i - 1];
 
          // Push it in a vector
          v.Add(el);
        }
 
        // Update the maximum
        // overall sum
        maxSum = Math.Max(maxSum, kadane(v));
      }
    }
 
    // Print the answer
    Console.Write(maxSum+ "\n");
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int [,]matrix = { { 0, -2, -7, 0 },
                      { 9, 2, -6, 2 },
                      { -4, 1, -4, 1 },
                      { -1, 8, 0, -2 } };
 
    // Function Call
    maxSubmatrixSum(matrix);
  }
}
 
// This code is contributed by 29AjayKumar


输出:
15

时间复杂度: O(N 6 )
辅助空间: O(1)

使用Kadane算法的有效方法:可以通过以下观察来优化上述方法:

  • 修复所需子矩阵的开始和结束列,分别说开始结束
  • 现在,迭代每一行,并将行总和从开始到结束列添加到sumSubmatrix并将其插入数组中。迭代每一行后,在这个新创建的数组上执行Kadane算法。如果通过应用Kadane算法获得的总和大于总的最大和,请更新总的最大和。
  • 在上述步骤中,可以通过创建大小为N * M的辅助矩阵(包含每行的前缀和),以恒定的时间计算从开始到结束的行的和。

请按照以下步骤解决问题:

  • 初始化一个变量,例如maxSum为INT_MIN,以存储最大子数组和。
  • 创建一个矩阵prefMatrix [N] [M] ,该矩阵存储给定矩阵每一行的前缀数组和。
  • 使用i作为行索引并使用j作为列索引逐行遍历矩阵,然后执行以下步骤:
    • 如果i的值为0 ,则设置prefMatrix [i] [j] = A [i] [j]
    • 否则,设置prefMatrix [i] [j] = prefMatrix [i] [j – 1] + A [i] [j]
  • 现在,对于[0,M]范围内子矩阵的列的开始和结束索引的所有可能组合,请执行以下步骤:
    • 初始化辅助数组A []以存储当前子矩阵每一行的最大和。
    • 使用prefMatrix查找从开始到结束的列和,如下所示:
      • 如果start的值为正,则将所需的总和S存储为prefMatrix [i] [end] – prefMatrix [i] [start – 1]
      • 否则,将S更新为prefMatrix [i] [end]
    • S插入数组arr []中
    • 迭代子矩阵中的所有行之后,对数组A []执行Kadane算法,并将最大和maxSum更新为maxSum和通过执行此步骤中的Kadane算法获得的值的最大值。
  • 完成上述步骤后,输出maxSum的值作为结果。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function to find maximum continuous
// maximum sum in the array
int kadane(vector v)
{
   
    // Stores current and maximum sum
    int currSum = 0;
    int maxSum = INT_MIN;
 
    // Traverse the array v
    for (int i = 0;
         i < (int)v.size(); i++) {
 
        // Add the value of the
        // current element
        currSum += v[i];
 
        // Update the maximum sum
        if (currSum > maxSum) {
            maxSum = currSum;
        }
 
        if (currSum < 0) {
            currSum = 0;
        }
    }
 
    // Return the maximum sum
    return maxSum;
}
 
// Function to find the maximum
// submatrix sum
void maxSubmatrixSum(
    vector > A)
{
   
    // Store the rows and columns
    // of the matrix
    int r = A.size();
    int c = A[0].size();
 
    // Create an auxiliary matrix
    int** prefix = new int*[r];
 
    // Traverse the matrix, prefix
    // and initialize it will all 0s
    for (int i = 0; i < r; i++) {
 
        prefix[i] = new int;
        for (int j = 0; j < c; j++) {
            prefix[i][j] = 0;
        }
    }
 
    // Calculate prefix sum of all
    // rows of matrix A[][] and
    // store in matrix prefix[]
    for (int i = 0; i < r; i++) {
 
        for (int j = 0; j < c; j++) {
 
            // Update the prefix[][]
            if (j == 0)
                prefix[i][j] = A[i][j];
            else
                prefix[i][j] = A[i][j]
                               + prefix[i][j - 1];
        }
    }
 
    // Store the maximum submatrix sum
    int maxSum = INT_MIN;
 
    // Iterate for starting column
    for (int i = 0; i < c; i++) {
 
        // Iterate for last column
        for (int j = i; j < c; j++) {
 
            // To store current array
            // elements
            vector v;
 
            // Traverse every row
            for (int k = 0; k < r; k++) {
 
                // Store the sum of the
                // kth row
                int el = 0;
 
                // Update the prefix
                // sum
                if (i == 0)
                    el = prefix[k][j];
                else
                    el = prefix[k][j]
                         - prefix[k][i - 1];
 
                // Push it in a vector
                v.push_back(el);
            }
 
            // Update the maximum
            // overall sum
            maxSum = max(maxSum, kadane(v));
        }
    }
 
    // Print the answer
    cout << maxSum << "\n";
}
 
// Driver Code
int main()
{
    vector > matrix = { { 0, -2, -7, 0 },
                                    { 9, 2, -6, 2 },
                                    { -4, 1, -4, 1 },
                                    { -1, 8, 0, -2 } };
 
    // Function Call
    maxSubmatrixSum(matrix);
 
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
class GFG{
 
  // Function to find maximum continuous
  // maximum sum in the array
  static int kadane(Vector v)
  {
 
    // Stores current and maximum sum
    int currSum = 0;
    int maxSum = Integer.MIN_VALUE;
 
    // Traverse the array v
    for (int i = 0;
         i < (int)v.size(); i++)
    {
 
      // Add the value of the
      // current element
      currSum += v.get(i);
 
      // Update the maximum sum
      if (currSum > maxSum)
      {
        maxSum = currSum;
      }
 
      if (currSum < 0)
      {
        currSum = 0;
      }
    }
 
    // Return the maximum sum
    return maxSum;
  }
 
  // Function to find the maximum
  // submatrix sum
  static void maxSubmatrixSum(int [][]A)
  {
    // Store the rows and columns
    // of the matrix
    int r = A.length;
    int c = A[0].length;
 
    // Create an auxiliary matrix
    int [][]prefix = new int[r][];
 
    // Traverse the matrix, prefix
    // and initialize it will all 0s
    for (int i = 0; i < r; i++) {
 
      prefix[i] = new int;
      for (int j = 0; j < c; j++) {
        prefix[i][j] = 0;
      }
    }
 
    // Calculate prefix sum of all
    // rows of matrix A[][] and
    // store in matrix prefix[]
    for (int i = 0; i < r; i++) {
 
      for (int j = 0; j < c; j++) {
 
        // Update the prefix[][]
        if (j == 0)
          prefix[i][j] = A[i][j];
        else
          prefix[i][j] = A[i][j]
          + prefix[i][j - 1];
      }
    }
 
    // Store the maximum submatrix sum
    int maxSum = Integer.MIN_VALUE;
 
    // Iterate for starting column
    for (int i = 0; i < c; i++) {
 
      // Iterate for last column
      for (int j = i; j < c; j++) {
 
        // To store current array
        // elements
        Vector v = new Vector();
 
        // Traverse every row
        for (int k = 0; k < r; k++) {
 
          // Store the sum of the
          // kth row
          int el = 0;
 
          // Update the prefix
          // sum
          if (i == 0)
            el = prefix[k][j];
          else
            el = prefix[k][j]
            - prefix[k][i - 1];
 
          // Push it in a vector
          v.add(el);
        }
 
        // Update the maximum
        // overall sum
        maxSum = Math.max(maxSum, kadane(v));
      }
    }
 
    // Print the answer
    System.out.print(maxSum+ "\n");
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int [][]matrix = { { 0, -2, -7, 0 },
                      { 9, 2, -6, 2 },
                      { -4, 1, -4, 1 },
                      { -1, 8, 0, -2 } };
 
    // Function Call
    maxSubmatrixSum(matrix);
  }
}
 
// This code is contributed by 29AjayKumar

Python3

# Python3 program for the above approach
import sys
 
# Function to find maximum continuous
# maximum sum in the array
def kadane(v):
     
    # Stores current and maximum sum
    currSum = 0
     
    maxSum = -sys.maxsize - 1
     
    # Traverse the array v
    for i in range(len(v)):
         
        # Add the value of the
        # current element
        currSum += v[i]
         
        # Update the maximum sum
        if (currSum > maxSum):
            maxSum = currSum
        if (currSum < 0):
            currSum = 0
     
    # Return the maximum sum
    return maxSum
 
# Function to find the maximum
# submatrix sum
def maxSubmatrixSum(A):
     
    # Store the rows and columns
    # of the matrix
    r = len(A)
    c = len(A[0])
     
    # Create an auxiliary matrix
    # Traverse the matrix, prefix
    # and initialize it will all 0s
    prefix = [[0 for i in range(c)]
                 for j in range(r)]
     
    # Calculate prefix sum of all
    # rows of matrix A[][] and
    # store in matrix prefix[]
    for i in range(r):
        for j in range(c):
             
            # Update the prefix[][]
            if (j == 0):
                prefix[i][j] = A[i][j]
            else:
                prefix[i][j] = A[i][j] + prefix[i][j - 1]
     
    # Store the maximum submatrix sum
    maxSum = -sys.maxsize - 1
     
    #  Iterate for starting column
    for i in range(c):
         
        # Iterate for last column
        for j in range(i, c):
             
            # To store current array
            # elements
            v = []
             
            # Traverse every row
            for k in range(r):
                 
                # Store the sum of the
                # kth row
                el = 0
                 
                # Update the prefix
                # sum
                if (i == 0):
                    el = prefix[k][j]
                else:
                    el = prefix[k][j] - prefix[k][i - 1]
                 
                # Push it in a vector
                v.append(el)
             
            # Update the maximum
            # overall sum
            maxSum = max(maxSum, kadane(v))
     
    # Print the answer
    print(maxSum)
 
# Driver Code
matrix = [ [ 0, -2, -7, 0 ],
           [ 9, 2, -6, 2 ],
           [ -4, 1, -4, 1 ],
           [ -1, 8, 0, -2 ] ]
            
# Function Call
maxSubmatrixSum(matrix)
 
# This code is contributed by rag2127

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG{
 
  // Function to find maximum continuous
  // maximum sum in the array
  static int kadane(List v)
  {
 
    // Stores current and maximum sum
    int currSum = 0;
    int maxSum = int.MinValue;
 
    // Traverse the array v
    for (int i = 0;
         i < (int)v.Count; i++)
    {
 
      // Add the value of the
      // current element
      currSum += v[i];
 
      // Update the maximum sum
      if (currSum > maxSum)
      {
        maxSum = currSum;
      }
 
      if (currSum < 0)
      {
        currSum = 0;
      }
    }
 
    // Return the maximum sum
    return maxSum;
  }
 
  // Function to find the maximum
  // submatrix sum
  static void maxSubmatrixSum(int [,]A)
  {
    // Store the rows and columns
    // of the matrix
    int r = A.GetLength(0);
    int c = A.GetLength(1);
 
    // Create an auxiliary matrix
    int [,]prefix = new int[r,c];
 
    // Traverse the matrix, prefix
    // and initialize it will all 0s
    for (int i = 0; i < r; i++) {
      for (int j = 0; j < c; j++) {
        prefix[i,j] = 0;
      }
    }
 
    // Calculate prefix sum of all
    // rows of matrix [,]A and
    // store in matrix prefix[]
    for (int i = 0; i < r; i++) {
 
      for (int j = 0; j < c; j++) {
 
        // Update the prefix[,]
        if (j == 0)
          prefix[i,j] = A[i,j];
        else
          prefix[i,j] = A[i,j]
          + prefix[i,j - 1];
      }
    }
 
    // Store the maximum submatrix sum
    int maxSum = int.MinValue;
 
    // Iterate for starting column
    for (int i = 0; i < c; i++) {
 
      // Iterate for last column
      for (int j = i; j < c; j++) {
 
        // To store current array
        // elements
        List v = new List();
 
        // Traverse every row
        for (int k = 0; k < r; k++) {
 
          // Store the sum of the
          // kth row
          int el = 0;
 
          // Update the prefix
          // sum
          if (i == 0)
            el = prefix[k,j];
          else
            el = prefix[k,j]
            - prefix[k,i - 1];
 
          // Push it in a vector
          v.Add(el);
        }
 
        // Update the maximum
        // overall sum
        maxSum = Math.Max(maxSum, kadane(v));
      }
    }
 
    // Print the answer
    Console.Write(maxSum+ "\n");
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int [,]matrix = { { 0, -2, -7, 0 },
                      { 9, 2, -6, 2 },
                      { -4, 1, -4, 1 },
                      { -1, 8, 0, -2 } };
 
    // Function Call
    maxSubmatrixSum(matrix);
  }
}
 
// This code is contributed by 29AjayKumar
输出:
15

时间复杂度: O(N 3 )
辅助空间: O(N 2 )