在 C++ 中删除最多一个元素后最大化最大子数组和
问题陈述
给定一个由 N 个整数组成的数组 arr[]。任务是首先找到最大子数组和,然后从该子数组中最多移除一个元素。最多移除单个元素,以使移除后的最大和最大化。
如果给定的输入数组为 {1, 2, 3, -2, 3},则最大子数组和为 {2, 3, -2, 3}。然后,我们可以移除 -2。移除后,其余数组变为-
{1, 2, 3, 3} with sum 9 which is maximum.
算法
1. Use Kadane’s algorithm to find the maximum subarray sum. 2. Once the sum has beens find, re-apply Kadane’s algorithm to find the maximum sum again with some minor changes)
示例
#include <bits/stdc++.h> using namespace std; int getMaxSubarraySum(int *arr, int n){ int max = INT_MIN; int currentMax = 0; for (int i = 0; i < n; ++i) { currentMax = currentMax + arr[i]; if (max < currentMax) { max = currentMax; } if (currentMax < 0) { currentMax = 0; } } return max; } int getMaxSum(int *arr, int n){ int cnt = 0; int minVal = INT_MAX; int minSubarr = INT_MAX; int sum = getMaxSubarraySum(arr, n); int max = INT_MIN; int currentMax = 0; for (int i = 0; i < n; ++i) { currentMax = currentMax + arr[i]; ++cnt; minSubarr = min(arr[i], minSubarr); if (sum == currentMax) { if (cnt == 1) { minVal = min(minVal, 0); } else { minVal = min(minVal, minSubarr); } } if (currentMax < 0) { currentMax = 0; cnt = 0; minSubarr = INT_MAX; } } return sum - minVal; } int main(){ int arr[] = {1, 2, 3, -2, 3}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum sum = " << getMaxSum(arr, n) << endl; return 0; }
输出
当您编译并执行上述程序时。它生成以下输出-
Maximum sum = 9
广告