Maximum Sum Contiguous subarray with unique elements.

Given a non-empty array of length n with non-negative elements. Write a program to find and return the maximum sum of a contiguous

subarray of the given array such that no two elements are repeated in the subarray.

Input: 1 2 3 3 4 5 2 1
Output: 15
Explanation: Subarray from index 3 to 7 constitutes the sum 15(3+4+5+2+1)


We will use two pointers i and j. We will use HashSet to store the elements of the ARRAY and update sum and j.

And once we encounter an element which is already in our set, we will remove all the elements from set preceding the repeated element, while incrementing i and updating our sum variable.


import java.lang.Math;
import java.util.*;
public class Main
//function to calculate maximum sum array
public static int longestSubarray(int[] arr) {

int i = 0, j = 1, currLength = 1;
HashSet<Integer> set = new HashSet<Integer>();

int sum= arr[0];// current max sum
int maxsum=sum;// GLobal maximum sum

while (i < arr.length - 1 && j < arr.length) {
// update sum and maxsum and increment j
if (!set.contains(arr[j])) {
// update sum and increment i and remove arr[i] from set
else {

return maxsum;

//Driver code
public static void main(String[] args) {
int arr[] = new int[]{ 1,2,3,4,1,1,9,4 };
int ans = longestSubarray(arr);



  • Time: O(n)
  • Auxiliary Space: O(n)




Love podcasts or audiobooks? Learn on the go with our new app.

CI/CD of microservices architecture with GitLab — Pt. 2

Are we really prioritizing the most important things for our products?

How I made a Service like S3 over the weekend

How to use Docker Swarm secrets to store and rotate your SSL certificates with Nginx reverse proxy

Google App Script — Take Your Automation To The Next Level

My First BrightCode Class

Method Overloading in Java

Portfolio Project: JobWin

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhinay Gupta

Abhinay Gupta

More from Medium


An Introduction to Linked Lists

Binary Search(4) / Algorithm

Greedy Algorithm