- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

In this tutorial, we will be discussing a program to find maximum sum subarray such that start and end values are same.

For this we will be provided with an array containing integers. Our task is to find the subarray with the maximum sum such that the elements are both its ends are equal.

## Example

#include <bits/stdc++.h> using namespace std; //finding the maximum sum int maxValue(int a[], int n) { unordered_map<int, int> first, last; int pr[n]; pr[0] = a[0]; for (int i = 1; i < n; i++) { pr[i] = pr[i - 1] + a[i]; if (first[a[i]] == 0) first[a[i]] = i; last[a[i]] = i; } int ans = 0; for (int i = 0; i < n; i++) { int start = first[a[i]]; int end = last[a[i]]; ans = max(ans, pr[end] - pr[start - 1]); } return ans; } int main() { int arr[] = { 1, 3, 5, 2, 4, 18, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxValue(arr, n); return 0; }

## Output

37

- Related Questions & Answers
- Maximum sum subarray such that start and end values are same in C++ Program
- Maximum length of subarray such that sum of the subarray is even in C++
- Maximum subsequence sum such that no three are consecutive
- Maximum subarray size, such that all subarrays of that size have sum less than k in C++
- Maximum sum such that no two elements are adjacent in C++
- Maximum subarray size, such that all subarrays of that size have sum less than k in C++ program
- Maximum subsequence sum such that no three are consecutive in C++ Program
- Maximum sum such that no two elements are adjacent - Set 2 in C++
- Maximum sum in circular array such that no two elements are adjacent in C++
- Maximum sum such that no two elements are adjacent Alternate Method in C++ program
- Maximum sum from three arrays such that picking elements consecutively from same is not allowed in C++
- Maximum Sum Circular Subarray in C++
- Maximum sum bitonic subarray in C++
- Maximum circular subarray sum in C++
- Maximum sum of nodes in Binary tree such that no two are adjacent in C++

Advertisements