C ++中排除某些元素的最大子数组总和
在本教程中,我们将讨论一个程序,以查找不包括某些元素的最大子数组总和。
为此,我们将提供两个大小为M和N的数组。我们的任务是在第一个数组中找到一个子数组,以使第二个数组中不存在该子数组中的元素,并且该子数组的元素总和为最大。
示例
#include <bits/stdc++.h>
using namespace std;
//检查第二个数组中是否存在元素
bool isPresent(int B[], int m, int x) {
for (int i = 0; i < m; i++)
if (B[i] == x)
return true;
return false;
}
int findMaxSubarraySumUtil(int A[], int B[], int n, int m) {
int max_so_far = INT_MIN, curr_max = 0;
for (int i = 0; i < n; i++) {
if (isPresent(B, m, A[i])) {
curr_max = 0;
continue;
}
curr_max = max(A[i], curr_max + A[i]);
max_so_far = max(max_so_far, curr_max);
}
return max_so_far;
}
void findMaxSubarraySum(int A[], int B[], int n, int m) {
int maxSubarraySum = findMaxSubarraySumUtil(A, B, n, m);
if (maxSubarraySum == INT_MIN) {
cout << "Maximum Subarray Sum cant be found" << endl;
} else {
cout << "The Maximum Subarray Sum = " << maxSubarraySum << endl;
}
}
int main() {
int A[] = { 3, 4, 5, -4, 6 };
int B[] = { 1, 8, 5 };
int n = sizeof(A) / sizeof(A[0]);
int m = sizeof(B) / sizeof(B[0]);
findMaxSubarraySum(A, B, n, m);
return 0;
}输出结果
The Maximum Subarray Sum = 7
热门推荐
1 狗狗下楼训练
3 狗狗训练头盔
6 狗狗训练机构
7 训练狗狗步骤
9 狗狗能训练
10 狗狗基本动作训练方法
11 怎么训练狗狗叼饭盆
12 狗狗一岁了还能训练吗
13 训练狗狗的
14 宁波狗狗训练
15 训练狗狗拉屎
16 教狗狗训练
17 狗狗要怎么训练上厕所
18 狗狗靠的训练