📜  最大和子矩阵

📅  最后修改于: 2021-09-04 11:20:35             🧑  作者: 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.


Javascript


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更新为该步骤执行Kadane算法得到的maxSum和value的最大值。
  • 完成以上步骤后,打印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

蟒蛇3

# 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 )

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live