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 = 15Input: 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:
- Initialize two pointers i and j as 0 and 1 respectively to store the starting and ending index of the resultant subarray.
- Initialize a HashSet to store the array elements.
- 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.
- 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.
- Repeat the above steps for the rest of the array and keep updating the max_sum.
- Print the maximum sum obtained after completing the above steps.
Below is the implementation of the above approach:
C++
// C++ program for// the above approach#include<bits/stdc++.h>using namespace std;// Function to calculate required// maximum subarray sumint 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[0]); // Current max sum int sum = arr[0]; // 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 Codeint 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
// Java program for the above approachimport 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<Integer> set = new HashSet<Integer>(); // 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
# Python3 program for the above approach# Function to calculate required# maximum subarray sumdef 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 Codeif __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#
// C# program for the above approachusing 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[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 Console.WriteLine(ans); }}// This code is contributed by shikhasingrajput |
Javascript
<script>// Javascript program for// the above approach// Function to calculate required// maximum subarray sumfunction maxSumSubarray(arr, n){ // Initialize two pointers var i = 0, j = 1; // Stores the unique elements var set = new Set(); // Insert the first element set.add(arr[0]); // Current max sum var sum = arr[0]; // Global maximum sum var maxsum = sum; while (i < n - 1 && j < n) { // Update sum & increment j // auto pos = s.find(3); var is_in = set.has(arr[j]); if (!is_in) { 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.delete(arr[i++]); } } // Return the maximum sum return maxsum;}// Driver Code// Given array arr[]var arr = [ 1, 2, 3, 1, 5 ];// Function Callvar ans = maxSumSubarray(arr, 5);// Print the maximum sumdocument.write(ans);// This code is contributed by rutvik_56</script> |
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.



