/** @brief * 给定一个数组arr,返回子数组的最大累加和 * arr=[1,-2,3,5,-2,6,-1],所有的子数组中,[3,5,-2,6]可以累加出最大的和12 * * @param arr[] int * @param length int * @return int * */ int MaxSubSum(int arr[], int length) { int ret = INT_MIN; int sum = 0; for(int i = 0; i < length; ++i) { sum += arr[i]; ret = max(sum, ret); if(sum < 0) sum = 0; } return ret; }
/** @brief * 找到两个不相容子数组的最大和(子数组不能为空) * 不相容,即下标区间不重叠 * 数组[1,-1,0,-2,3,5,-2,8,7,-4],两个不相容子数组分别为[3,5]和[8,7]时累加和最大 * 数组[3,-1,0,-2,3,5,-2,8,7,-4],两个不相容子数组分别为[3]和[3,5,-2,8,7]时累加和最大 * * @param arr[] int * @param length int * @return int * */ int TwoSubarrayMaxSum(int arr[], int length) { int *pSums = new int[length]; int maxSum = INT_MIN; int sum = 0; for(int i = 0; i < length; ++i) { sum += arr[i]; maxSum = max(maxSum, sum); pSums[i] = maxSum; if(sum < 0) sum = 0; } int ret = INT_MIN; sum = 0; maxSum = INT_MIN; for(int i = length - 1; i > 0; --i) { sum += arr[i]; maxSum = max(maxSum, sum); pSums[i] = maxSum; if(sum < 0) sum = 0; ret = max(ret, pSums[i] + pSums[i - 1]); } delete[] pSums; return ret; }
/** @brief * 子矩阵的最大累加和问题 * 给定一个矩阵matrix,其中的值有正、有负、有0,返回子矩阵的最大累加和。 * * @param matrix vector<vector<int> > -矩阵 * @param row int -矩阵行数 * @param column int -矩阵列数 * @return int * */ int MaxSubMatrixSum(vector<vector<int> > matrix, int row, int column) { int *pNums = new int[column]; int ret = INT_MIN; for(int i = 0; i < row; ++i) { memset(pNums, 0, sizeof(int) * column); for(int j = i; j < row; ++j) { for(int col = 0; col < column; ++col) { pNums[col] += matrix[j][col]; } ret = max(ret, MaxSubSum(pNums, column)); } } delete[] pNums; return ret; }