Maximum subarray sum in array formed by repeating the given array k times in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array and a number k. Our task is to create a program that will find the maximum subarray sum in an array formed by repeating the given array k time in c++.

Problem description − Here, we will find the maximum sum of the subarray formed from array formed by repeating the given array k times.

Let’s take an example to understand the problem,

Input − array = {3, 5, 1} k = 2

Output − 18

Explanation

array formed by repeating k times,
array = {3, 5, 1, 3, 5, 1}
Maximum subarray sum = 3+5+1+3+5+1 = 18

To solve this problem, we will calculate the sum of all elements of the array.

Then based on the sum, we will calculate the subarray sum calculation.

If sum > 0, we will multiply the sum of array k times which given the actual sum.

If sum < 0, we will find the subarray with maxSum taking two array repetitions.

Example

Program to show the implementation of our solution,

 Live Demo

#include<iostream>
using namespace std;
void repeatArray(int *arr, int *b, int k,int len) {
   int j = 0;
   while (k > 0){
      for (int i = 0; i < len; i++)
      b[j++] = arr[i];
      k--;
   }
}
long subArraySum(int *a,int len) {
   int max = 0;
   long newmax = 0;
   for (int i = 0; i < len; i++) {
      newmax = newmax + a[i];
   if (max < newmax)
      max = newmax;
   if (newmax < 0)
      newmax = 0;
   }
   return max;
}
long findMaxSubArraySum(int *arr, int k,int len) {
   int arraySum = 0;
   long maxSum = 0;
   int b[(2 * len)]= {0};
   repeatArray(arr, b, 2,len);
   for (int i = 0; i < len; i++)
   arraySum += arr[i];
   maxSum = subArraySum(b,2*len);
   if (arraySum > 0)
      maxSum = subArraySum(b,2*len) + (k - 2) * arraySum;
   return maxSum;
}
int main() {
   int arr[] = { 3, 5, 1};
   int length=sizeof(arr)/sizeof(arr[0]);
   int k = 3;
   cout<<"The maximum subarray sum in array formed by repeating the given array "<<k<<" times is "<<findMaxSubArraySum(arr, k,length);
   return 0;
}

Output

The maximum subarray sum in array formed by repeating the given array 3 times is 27
raja
Published on 30-Jan-2020 11:59:24
Advertisements