# Maximum possible sum of a window in an array such that elements of same window in other array are unique

• Difficulty Level : Medium
• Last Updated : 15 Jul, 2022

Given two arrays A and B of equal number of elements. Task is to find the maximum sum possible of a window in array B such that elements of same window in A[] are unique.

Examples:

```Input : A = [0, 1, 2, 3, 0, 1, 4]
B = [9, 8, 1, 2, 3, 4, 5]
Output : sum = 20
The maximum sum possible in B[] such that
all corresponding elements in A[] are unique
is (9+8+1+2) = 20.

Input : A = [0, 1, 2, 0, 2]
B = [5, 6, 7, 8, 2]
Output :sum = 21```

A simple solution is to consider all sub-arrays of B[]. For every sub-array, check if elements same sub-array in A[] are distinct or not. If distinct, then compare sum with result and update result.

Time complexity: O(n2), as we will be using nested loops for checking every sub-array.
Auxiliary Space: O(1), as we are not using any extra space.

An efficient solution is to use hashing.

1. Create an empty hash table.
2. Traverse array elements. Do following for every element A[i].
• While A[i] is present in hash table, keep removing elements from beginning of current window and keep subtracting window beginning element of B[] from current sum.
3. Add B[i] to current sum and update result if current sum becomes more.
4. Return result.

Below is the implementation of above steps.

## C++

 `// C++ program to find the maximum``// possible sum of a window in one``// array such that elements in same``// window of other array are unique.``#include ``using` `namespace` `std;` `// Function to return maximum sum of window``// in B[] according to given constraints.``int` `returnMaxSum(``int` `A[], ``int` `B[], ``int` `n)``{``    ``// Map is used to store elements``    ``// and their counts.``    ``unordered_set<``int``> mp;` `    ``int` `result = 0; ``// Initialize result` `    ``// calculating the maximum possible``    ``// sum for each subarray containing``    ``// unique elements.``    ``int` `curr_sum = 0, curr_begin = 0;``    ``for` `(``int` `i = 0; i < n; ++i) {` `        ``// Remove all duplicate``        ``// instances of A[i] in``        ``// current window.``        ``while` `(mp.find(A[i]) != mp.end()) {``            ``mp.erase(A[curr_begin]);``            ``curr_sum -= B[curr_begin];``            ``curr_begin++;``        ``}` `        ``// Add current instance of A[i]``        ``// to map and to current sum.``        ``mp.insert(A[i]);``        ``curr_sum += B[i];` `        ``// Update result if current``        ``// sum is more.``        ``result = max(result, curr_sum);``    ``}` `    ``return` `result;``}` `// Driver code``int` `main()``{``    ``int` `A[] = { 0, 1, 2, 3, 0, 1, 4 };``    ``int` `B[] = { 9, 8, 1, 2, 3, 4, 5 };``    ``int` `n = ``sizeof``(A)/``sizeof``(A[0]);``    ``cout << returnMaxSum(A, B, n);``    ``return` `0;``}`

## Java

 `// Java program to find the maximum``// possible sum of a window in one``// array such that elements in same``// window of other array are unique.``import` `java.util.HashSet;``import` `java.util.Set;` `public` `class` `MaxPossibleSuminWindow``{``    ``// Function to return maximum sum of window``    ``// in A[] according to given constraints.``    ``static` `int` `returnMaxSum(``int` `A[], ``int` `B[], ``int` `n)``    ``{` `        ``// Map is used to store elements``        ``// and their counts.``        ``Set mp = ``new` `HashSet();` `        ``int` `result = ``0``; ``// Initialize result` `        ``// calculating the maximum possible``        ``// sum for each subarray containing``        ``// unique elements.``        ``int` `curr_sum = ``0``, curr_begin = ``0``;``        ``for` `(``int` `i = ``0``; i < n; ++i)``        ``{``            ``// Remove all duplicate``            ``// instances of A[i] in``            ``// current window.``            ``while` `(mp.contains(A[i]))``            ``{``                ``mp.remove(A[curr_begin]);``                ``curr_sum -= B[curr_begin];``                ``curr_begin++;``            ``}` `            ``// Add current instance of A[i]``            ``// to map and to current sum.``            ``mp.add(A[i]);``            ``curr_sum += B[i];` `            ``// Update result if current``            ``// sum is more.``            ``result = Integer.max(result, curr_sum);` `        ``}``        ``return` `result;``    ``}` `    ``//Driver Code to test above method``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `A[] = { ``0``, ``1``, ``2``, ``3``, ``0``, ``1``, ``4` `};``        ``int` `B[] = { ``9``, ``8``, ``1``, ``2``, ``3``, ``4``, ``5` `};``        ``int` `n = A.length;``        ``System.out.println(returnMaxSum(A, B, n));``    ``}``}``// This code is contributed by Sumit Ghosh`

## Python3

 `# Python3 program to find the maximum``# possible sum of a window in one``# array such that elements in same``# window of other array are unique.` `# Function to return maximum sum of window``# in B[] according to given constraints.``def` `returnMaxSum(A, B, n):`` ` `    ``# Map is used to store elements``    ``# and their counts.``    ``mp ``=` `set``()``    ``result ``=` `0` `# Initialize result` `    ``# calculating the maximum possible``    ``# sum for each subarray containing``    ``# unique elements.``    ``curr_sum ``=` `curr_begin ``=` `0``    ``for` `i ``in` `range``(``0``, n): ` `        ``# Remove all duplicate instances``        ``# of A[i] in current window.``        ``while` `A[i] ``in` `mp: ``            ``mp.remove(A[curr_begin])``            ``curr_sum ``-``=` `B[curr_begin]``            ``curr_begin ``+``=` `1``         ` `        ``# Add current instance of A[i]``        ``# to map and to current sum.``        ``mp.add(A[i])``        ``curr_sum ``+``=` `B[i]` `        ``# Update result if current``        ``# sum is more.``        ``result ``=` `max``(result, curr_sum)``     ` `    ``return` `result` `# Driver code``if` `__name__ ``=``=` `"__main__"``:`` ` `    ``A ``=` `[``0``, ``1``, ``2``, ``3``, ``0``, ``1``, ``4``] ``    ``B ``=` `[``9``, ``8``, ``1``, ``2``, ``3``, ``4``, ``5``]``    ``n ``=` `len``(A)``    ``print``(returnMaxSum(A, B, n))` `# This code is contributed by Rituraj Jain`

## C#

 `// C# program to find the maximum``// possible sum of a window in one``// array such that elements in same``// window of other array are unique.``using` `System;``using` `System.Collections.Generic;` `public` `class` `MaxPossibleSuminWindow``{``    ` `    ``// Function to return maximum sum of window``    ``// in A[] according to given constraints.``    ``static` `int` `returnMaxSum(``int` `[]A, ``int` `[]B, ``int` `n)``    ``{` `        ``// Map is used to store elements``        ``// and their counts.``        ``HashSet<``int``> mp = ``new` `HashSet<``int``>();` `        ``int` `result = 0; ``// Initialize result` `        ``// calculating the maximum possible``        ``// sum for each subarray containing``        ``// unique elements.``        ``int` `curr_sum = 0, curr_begin = 0;``        ``for` `(``int` `i = 0; i < n; ++i)``        ``{``            ``// Remove all duplicate``            ``// instances of A[i] in``            ``// current window.``            ``while` `(mp.Contains(A[i]))``            ``{``                ``mp.Remove(A[curr_begin]);``                ``curr_sum -= B[curr_begin];``                ``curr_begin++;``            ``}` `            ``// Add current instance of A[i]``            ``// to map and to current sum.``            ``mp.Add(A[i]);``            ``curr_sum += B[i];` `            ``// Update result if current``            ``// sum is more.``            ``result = Math.Max(result, curr_sum);` `        ``}``        ``return` `result;``    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main(String[] args)``    ``{``        ``int` `[]A = { 0, 1, 2, 3, 0, 1, 4 };``        ``int` `[]B = { 9, 8, 1, 2, 3, 4, 5 };``        ``int` `n = A.Length;``        ``Console.WriteLine(returnMaxSum(A, B, n));``    ``}``}` `/* This code has been contributed``by PrinciRaj1992*/`

## Javascript

 ``

Output

`20`

Time complexity: O(n), as we are using a loop to traverse N times and unordered map operations will take constant time. Where N is the number of elements in the array.
Auxiliary Space: O(N), as we are using extra space for the map. Where N is the number of elements in the array.

Note that every element of array is inserted and removed at most once from array.

This article is contributed by Parth Trehan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

My Personal Notes arrow_drop_up