給定 N×N 矩陣(N ≤ 100),元素為整數(可正可負),求任意子矩陣(連續行、連續列)的最大元素和。
top 從 0 到 N-1。colSum[N] = {0}。bottom 從 top 到 N-1,累加第 bottom 行到 colSum:for (int c=0; ccolSum 求最大子數組和(Kadane),更新全局答案。原理:固定上下邊界後,子矩陣列和即為 colSum 的連續子段和。
int maxSubArray(const vector& a) {
int maxEndingHere = a[0], maxSoFar = a[0];
for (size_t i=1; i
全負數組也能正確返回最大元素(而非 0)。
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N;
while (cin >> N) {
vector> mat(N, vector(N));
for (int i=0; i> mat[i][j];
int ans = INT_MIN;
vector colSum(N);
for (int top=0; top
left/right,外層記錄 top/bottom。HDU 1081 是二維最大子矩陣和的經典模板題。核心技巧:枚舉上下邊界壓縮列,轉化為一維最大子數組和。Kadane 演算法 O(N) 求解一維問題,整體 O(N^3) 完美適用 N≤100。此降維思想廣泛應用於圖像處理(最大亮度區域)、金融(多資產最大收益窗口)、基因組學(最大得分片段)等領域。