Maximum Subarray Sum in Repeated Concatenation Array in C++
In this tutorial, we will be discussing a program to find maximum subarray sum in an array created after repeated concatenation.
For this we will be provided with an array and an integer K. Our task is to find the subarray with the maximum elements when the given array is repeated K times.
Example
#include<bits/stdc++.h> using namespace std; //returning sum of maximum subarray int maxSubArraySumRepeated(int a[], int n, int k) { int max_so_far = INT_MIN, max_ending_here = 0; for (int i = 0; i < n*k; i++) { max_ending_here = max_ending_here + a[i%n]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far; } int main() { int a[] = {10, 20, -30, -1}; int n = sizeof(a)/sizeof(a[0]); int k = 3; cout << "Maximum contiguous sum is " << maxSubArraySumRepeated(a, n, k); return 0; }
Output
Maximum contiguous sum is 30
Advertisements