在这个问题中,我们得到一个正整数和一个数字k的数组。我们的任务是创建一个程序,该程序将找到给定大小(k)的两个不重叠子数组的最大和。
因此,基本上,我们有两个打印两个不重叠(不同)的子数组,它们的总和最大且大小为k。
让我们举个例子来了解这个问题,
输入-
array = {7, 1, 6, 9, 2} , k = 2
输出-
{7, 1} , {6, 9}
说明-
all subarrays of size 2. {7, 1} : sum = 7+1 = 8 {1, 6} : sum = 1+6 = 7 {6, 9} : sum = 6+9 = 15 {9, 2} : sum = 9+2 = 11 Two non-overlapping subarrays with max sums are {7,1} and {6,9}
为了解决这个问题,一个简单的解决方案是找到所有子数组及其和,然后检查两个不互相重叠的最大子数组。
解决此问题的有效方法是使用前缀和数组,该数组存储所有元素的和直到该数组的元素。然后检查k个元素的子数组以找到总和最大的子数组。
显示我们解决方案实施情况的程序,
#include <bits/stdc++.h> using namespace std; int findSubArraySum(int sum[], int i, int j){ if (i == 0) return sum[j]; else return (sum[j] - sum[i - 1]); } void maxSubarray(int arr[],int N, int K){ int prefixsum[N]; prefixsum[0] = arr[0]; for (int i = 1; i < N; i++) prefixsum[i] = prefixsum[i - 1] + arr[i]; pair<int, int> resIndex = make_pair(N - 2 * K, N - K); int maxSubarraySum = findSubArraySum(prefixsum, N - 2 * K, N - K - 1) + findSubArraySum(prefixsum, N - K, N - 1); pair<int, int> secondSubarrayMax = make_pair(N - K, findSubArraySum(prefixsum, N - K, N - 1)); for (int i = N - 2 * K - 1; i >= 0; i--){ int cur = findSubArraySum(prefixsum, i + K, i + 2 * K - 1); if (cur >= secondSubarrayMax.second) secondSubarrayMax = make_pair(i + K, cur); cur = findSubArraySum(prefixsum, i, i + K - 1) + secondSubarrayMax.second; if (cur >= maxSubarraySum){ maxSubarraySum = cur; resIndex = make_pair(i, secondSubarrayMax.first); } } cout<<"{ "; for (int i = resIndex.first; i <resIndex.first + K; i++) cout<<arr[i]<<" "; cout<<"}"<<endl<<"{ "; for (int i = resIndex.second; i < resIndex.second + K; i++) cout<<arr[i]<<" "; cout<<"}"<<endl; } int main(){ int arr[] = {2, 5, 1, 2, 7, 3, 0}; int N = sizeof(arr) / sizeof(int); int K = 2; cout<<"Two non-overlapping subarrays with maximum sum are \n"; maxSubarray(arr, N, K); return 0; }
输出结果
Two non-overlapping subarrays with maximum sum are { 2 5 } { 7 3 }