Maximum subarray sum in an array created after repeated concatenation in C++ Program


In this problem, we are given an array arr[] of size n and an integer k. Our task is to create a program to find the maximum subarray sum in an array created after repeated concatenation.

Problem Description − We will find the maximum sum of the subarray is taken from the array which is created after repeating arr, k times.

Example

Let’s take an example to understand the problem.

Input

arr[] = {−9, −5, 14, 6} k = 2

Output

26

Explanation

New array after repeating : {−9, −5, 14, 6, −9, −5, 14, 6}
Subarray with maximum sum = {14, 6, −9, −5, 14, 6}
Sum = 26

Solution Approach

A simple solution is to create a new array that will be formed after concatenating arr[], k time, and then find the subarray with maximum sum. For this, the best method would be using Kadane's Algorithm.

Example

Program to illustrate the working of our solution,

 Live Demo

#include <iostream>
using namespace std;
int calcMaxSubArraySum(int arr[], int n, int k){
   int newArr[2*n];
   for(int i = 0; i < k*n; i++)
   newArr[i] = arr[i%n];
   int maxSum = −1000, sum = 0;
   for (int i = 0; i < k*n; i++) {
      sum = sum + newArr[i];
      if (maxSum < sum)
         maxSum = sum;
      if (sum < 0)
         sum = 0;
   }
   return maxSum;
}
int main(){
   int arr[] = { −9, −5, 14, 6 };
   int k = 2;
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The maximum subarray sum in an array created after repeated concatenation is "<<calcMaxSubArraySum(arr, n, k);
   return 0;
}

Output

The maximum subarray sum in an array created after repeated
concatenation is 26

This approach is good but a more efficient approach to solving the problem is possible using modular arithmetic.

Modular Arithmetic is when we use the modulo operator to get the remainder of the equation.

To solve the problem, we will use modular arithmetic instead of creating the array by repeated concatenation. Rest solution remains the same.

Example

Program to illustrate the working our solution,

 Live Demo

#include <iostream>
using namespace std;
int calcMaxSubArraySum(int arr[], int n, int k){
   int maxSum = −1000, sum = 0;
   for (int i = 0; i < k*n; i++) {
      sum = sum + arr[i%n];
      if (maxSum < sum)
         maxSum = sum;
      if (sum < 0)
         sum = 0;
   }
   return maxSum;
}
int main(){
   int arr[] = { −9, −5, 14, 6 };
   int k = 2;
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The maximum subarray sum in an array created after
   repeated concatenation is "<<calcMaxSubArraySum(arr, n, k);
   return 0;
}

Output

The maximum subarray sum in an array created after repeated
concatenation is 26

Updated on: 09-Dec-2020

101 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements