# Largest Sum Contiguous Subarray having unique elements

Given an array arr[] of N positive integers, the task is to find the subarray having maximum sum among all subarrays having unique elements and print its sum.

Input arr[] = {1, 2, 3, 3, 4, 5, 2, 1}
Output: 15
Explanation:
The subarray having maximum sum with distinct element is {3, 4, 5, 2, 1}.
Therefore, sum is = 3 + 4 + 5 + 2 + 1 = 15

Input: arr[] = {1, 2, 3, 1, 5}
Output: 11
Explanation:
The subarray having maximum sum with distinct element is {2, 3, 1, 5}.
Therefore, sum is = 2 + 3 + 1 + 5 = 11.

Naive Approach: The simplest approach to solve the problem is to generate all possible subarrays and for each subarray, check if all its elements are unique or not. Find the maximum sum among such subarrays and print it.
Time Complexity: O(N3)
Auxiliary Space: O(N)

Efficient Approach: To optimize the above approach the idea is to use the Two Pointer technique. Follow the steps below to solve the approach:

1. Initialize two pointers i and j as 0 and 1 respectively to store the starting and ending index of the resultant subarray.
2. Initialize a HashSet to store the array elements.
3. Start from an empty subarray with i = 0 and j = 0 and traverse the array until any duplicate element is found and update the current sum to the maximum sum(say max_sum) if it is found to be greater than the current max_sum.
4. If the duplicate element is found, increment j and update the variables until only unique elements are left in the current subarray from index j to i.
5. Repeat the above steps for the rest of the array and keep updating the max_sum.
6. Print the maximum sum obtained after completing the above steps.

Below is the implementation of the above approach:

 `// C++ program for ` `// the above approach ` `#include` `using` `namespace` `std;`   `// Function to calculate required` `// maximum subarray sum` `int` `maxSumSubarray(``int` `arr[], ``int` `n)` `{` `  ``// Initialize two pointers` `  ``int` `i = 0, j = 1;` `  ``// Stores the unique elements` `  ``set<``int``> set;`   `  ``// Insert the first element` `  ``set.insert(arr);`   `  ``// Current max sum` `  ``int` `sum = arr;`   `  ``// Global maximum sum` `  ``int` `maxsum = sum;`   `  ``while` `(i < n - 1 && j < n) ` `  ``{` `    ``// Update sum & increment j` `    ``// auto pos = s.find(3); ` `    ``const` `bool` `is_in = set.find(arr[j]) != ` `                       ``set.end();` `    ``if` `(!is_in) ` `    ``{` `      ``sum = sum + arr[j];` `      ``maxsum = max(sum, maxsum);`   `      ``// Add the current element` `      ``set.insert(arr[j++]);` `    ``}`   `    ``// Update sum and increment i` `    ``// and remove arr[i] from set` `    ``else` `    ``{` `      ``sum -= arr[i];`   `      ``// Remove the element` `      ``// from start position` `      ``set.erase(arr[i++]);` `    ``}` `  ``}`   `  ``// Return the maximum sum` `  ``return` `maxsum;` `}`   `// Driver Code` `int`  `main()` `{` `  ``// Given array arr[]` `  ``int` `arr[] = {1, 2, 3, 1, 5};`   `  ``// Function Call` `  ``int` `ans = maxSumSubarray(arr, 5);`   `  ``// Print the maximum sum` `  ``cout << (ans);` `}`   `// This code is contributed by gauravrajput1`

 `// Java program for the above approach`   `import` `java.io.*;` `import` `java.lang.Math;` `import` `java.util.*;` `public` `class` `GFG {`   `    ``// Function to calculate required` `    ``// maximum subarray sum` `    ``public` `static` `int` `    ``maxSumSubarray(``int``[] arr)` `    ``{`   `        ``// Initialize two pointers` `        ``int` `i = ``0``, j = ``1``;`   `        ``// Stores the unique elements` `        ``HashSet set` `            ``= ``new` `HashSet();`   `        ``// Insert the first element` `        ``set.add(arr[``0``]);`   `        ``// Current max sum` `        ``int` `sum = arr[``0``];`   `        ``// Global maximum sum` `        ``int` `maxsum = sum;`   `        ``while` `(i < arr.length - ``1` `               ``&& j < arr.length) {`   `            ``// Update sum & increment j` `            ``if` `(!set.contains(arr[j])) {`   `                ``sum = sum + arr[j];` `                ``maxsum = Math.max(sum,` `                                  ``maxsum);`   `                ``// Add the current element` `                ``set.add(arr[j++]);` `            ``}`   `            ``// Update sum and increment i` `            ``// and remove arr[i] from set` `            ``else` `{`   `                ``sum -= arr[i];`   `                ``// Remove the element` `                ``// from start position` `                ``set.remove(arr[i++]);` `            ``}` `        ``}`   `        ``// Return the maximum sum` `        ``return` `maxsum;` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `        ``main(String[] args)` `    ``{` `        ``// Given array arr[]` `        ``int` `arr[] = ``new` `int``[] { ``1``, ``2``, ``3``, ``1``, ``5` `};`   `        ``// Function Call` `        ``int` `ans = maxSumSubarray(arr);`   `        ``// Print the maximum sum` `        ``System.out.println(ans);` `    ``}` `}`

 `# Python3 program for the above approach`   `# Function to calculate required` `# maximum subarray sum` `def` `maxSumSubarray(arr):`   `    ``# Initialize two pointers` `    ``i ``=` `0` `    ``j ``=` `1`   `    ``# Stores the unique elements` `    ``set` `=` `{}`   `    ``# Insert the first element` `    ``set``[arr[``0``]] ``=` `1`   `    ``# Current max sum` `    ``sum` `=` `arr[``0``]`   `    ``# Global maximum sum` `    ``maxsum ``=` `sum`   `    ``while` `(i < ``len``(arr) ``-` `1` `and` `           ``j < ``len``(arr)):`   `        ``# Update sum & increment j` `        ``if` `arr[j] ``not` `in` `set``:` `            ``sum` `=` `sum` `+` `arr[j]` `            ``maxsum ``=` `max``(``sum``, maxsum)`   `            ``# Add the current element` `            ``set``[arr[j]] ``=` `1` `            ``j ``+``=` `1`   `        ``# Update sum and increment i` `        ``# and remove arr[i] from set` `        ``else``:` `            ``sum` `-``=` `arr[i]`   `            ``# Remove the element` `            ``# from start position` `            ``del` `set``[arr[i]]` `            ``i ``+``=` `1`   `    ``# Return the maximum sum` `    ``return` `maxsum`   `# Driver Code` `if` `__name__ ``=``=` `'__main__'``:`   `    ``# Given array arr[]` `    ``arr ``=` `[ ``1``, ``2``, ``3``, ``1``, ``5` `]`   `    ``# Function call` `    ``ans ``=` `maxSumSubarray(arr)`   `    ``# Print the maximum sum` `    ``print``(ans)`   `# This code is contributed by mohit kumar 29`

 `// C# program for the above approach` `using` `System;` `using` `System.Collections.Generic;` `class` `GFG{`   `  ``// Function to calculate ` `  ``// required maximum subarray sum` `  ``public` `static` `int` `maxSumSubarray(``int``[] arr)` `  ``{` `    ``// Initialize two pointers` `    ``int` `i = 0, j = 1;`   `    ``// Stores the unique elements` `    ``HashSet<``int``> ``set` `= ` `            ``new` `HashSet<``int``>();`   `    ``// Insert the first element` `    ``set``.Add(arr);`   `    ``// Current max sum` `    ``int` `sum = arr;`   `    ``// Global maximum sum` `    ``int` `maxsum = sum;`   `    ``while` `(i < arr.Length - 1 && ` `           ``j < arr.Length) ` `    ``{` `      ``// Update sum & increment j` `      ``if` `(!``set``.Contains(arr[j])) ` `      ``{` `        ``sum = sum + arr[j];` `        ``maxsum = Math.Max(sum,` `                          ``maxsum);`   `        ``// Add the current element` `        ``set``.Add(arr[j++]);` `      ``}`   `      ``// Update sum and increment i` `      ``// and remove arr[i] from set` `      ``else` `      ``{` `        ``sum -= arr[i];`   `        ``// Remove the element` `        ``// from start position` `        ``set``.Remove(arr[i++]);` `      ``}` `    ``}`   `    ``// Return the maximum sum` `    ``return` `maxsum;` `  ``}`   `  ``// Driver Code` `  ``public` `static` `void` `Main(String[] args)` `  ``{` `    ``// Given array []arr` `    ``int` `[]arr = ``new` `int``[] {1, 2, ` `                           ``3, 1, 5};`   `    ``// Function Call` `    ``int` `ans = maxSumSubarray(arr);`   `    ``// Print the maximum sum` `    ``Console.WriteLine(ans);` `  ``}` `}`   `// This code is contributed by shikhasingrajput`

Output:
```11

```

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.