# Maximum sum subarray such that start and end values are same in C++ Program

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] of size n consisting of positive values. Our task is to create a program to find the maximum sum subarray such that start and end values are the same.

Problem Description − Here, we need to find a subarray such that the elements at index i (starting index of subarray) and j (ending index of subarray) are the same i.e. arr[i] = arr[j]. And the sum of elements of the subarray is maximized.

Let’s take an example to understand the problem,

## Input

arr[] = {2, 1, 3, 5, 6, 2, 4, 3}

## Output

23

## Explanation

All subarrays which are starting and ending with the same element are:
{2, 1, 3, 5, 6, 2} = 2 + 1 + 3 + 5 + 6 + 2 = 19
{3, 5, 6, 2, 4, 3} = 3 + 5 + 6 + 2 + 4 + 3 = 23

## Solution Approach

To solve the problem, we need to consider the fact that for positive values the sum of subarrays increases with the size of subarrays we consider. For this, we will find the subarray with maximum size by finding the leftmost and rightmost occurrence of numbers in the array. And return their sum if it is more than maxSum.

## Example

Program to illustrate the working of our solution,

Live Demo

#include <bits/stdc++.h>
using namespace std;
int maxValue(int arr[], int n) {
unordered_map<int, int> startIndex, endIndex;
int sumArr[n];
sumArr[0] = arr[0];
for (int i = 1; i < n; i++) {
sumArr[i] = sumArr[i − 1] + arr[i];
if (startIndex[arr[i]] == 0)
startIndex[arr[i]] = i;
endIndex[arr[i]] = i;
}
int maxSum = 0;
for (int i = 0; i < n; i++) {
int left = startIndex[arr[i]];
int right = endIndex[arr[i]];
maxSum = max(maxSum, sumArr[right] − sumArr[left − 1]);
}
return maxSum;
}
int main() {
int arr[] = { 2, 1, 3, 5, 6, 2, 4, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"The maximum sum subarray such that start and end values are same is "<<maxValue(arr, n);
return 0;
}

## Output

The maximum sum subarray such that start and end values are same is 23
Published on 09-Dec-2020 18:09:05