Maximum possible sum of a window in an array such that elements of same window in other array are unique
Last Updated :
07 Mar, 2023
Given two arrays A and B of equal number of elements. The 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.
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 <bits/stdc++.h>
using namespace std;
// Function to return maximum sum of window
// in B[] according to given constraints.
int returnMaxSum(int A[], int B[], int n)
{
int result = INT_MIN;
for (int i = 0; i < n; i++) {
unordered_map<int, int> unmap;
int sum = 0;
for (int j = i; j < n; j++) {
unmap[A[j]]++;
sum += B[j];
if (unmap.size() == (j - i + 1)) {
result = max(result, 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
import java.util.HashMap;
import java.util.Map;
public class Gfg {
static int returnMaxSum(int[] A, int[] B, int n)
{
int result = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
Map<Integer, Integer> unmap = new HashMap<>();
int sum = 0;
for (int j = i; j < n; j++) {
unmap.put(A[j],
unmap.getOrDefault(A[j], 0) + 1);
sum += B[j];
if (unmap.size() == (j - i + 1)) {
result = Math.max(result, sum);
}
}
}
return result;
}
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));
}
}
C#
using System;
using System.Collections.Generic;
class Gfg {
static int returnMaxSum(int[] A, int[] B, int n)
{
int result = int.MinValue;
for (int i = 0; i < n; i++) {
Dictionary<int, int> unmap
= new Dictionary<int, int>();
int sum = 0;
for (int j = i; j < n; j++) {
if (!unmap.ContainsKey(A[j]))
unmap.Add(A[j], 1);
else
unmap[A[j]]++;
sum += B[j];
if (unmap.Count == (j - i + 1)) {
result = Math.Max(result, sum);
}
}
}
return result;
}
public static void Main()
{
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));
}
}
Python3
# Python 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 sys
# Function to return maximum sum of window
# in B[] according to given constraints.
def returnMaxSum(A, B, n):
result = -sys.maxsize
for i in range(n):
unmap = {}
sum = 0
for j in range(i, n):
if A[j] in unmap:
unmap[A[j]] += 1
else:
unmap[A[j]] = 1
sum += B[j]
if len(unmap) == (j - i + 1):
result = max(result, 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))
JavaScript
// JavaScript equivalent of the above code
// Function to return maximum sum of window
// in B[] according to given constraints.
function returnMaxSum(A, B, n) {
let result = -Number.MAX_VALUE;
for (let i = 0; i < n; i++) {
let unmap = {};
let sum = 0;
for (let j = i; j < n; j++) {
if (A[j] in unmap) {
unmap[A[j]] += 1;
} else {
unmap[A[j]] = 1;
}
sum += B[j];
if (Object.keys(unmap).length == (j - i + 1)) {
result = Math.max(result, sum);
}
}
}
return result;
}
// Driver code
A = [0, 1, 2, 3, 0, 1, 4];
B = [9, 8, 1, 2, 3, 4, 5];
n = A.length;
console.log(returnMaxSum(A, B, n));
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.
- Create an empty hash table.
- 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.
- Add B[i] to current sum and update result if current sum becomes more.
- 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 <bits/stdc++.h>
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<Integer> mp = new HashSet<Integer>();
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
<script>
// Javascript 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.
function returnMaxSum(A, B, n)
{
// Map is used to store elements
// and their counts.
var mp = new Set();
var result = 0; // Initialize result
// calculating the maximum possible
// sum for each subarray containing
// unique elements.
var curr_sum = 0, curr_begin = 0;
for (var i = 0; i < n; ++i) {
// Remove all duplicate
// instances of A[i] in
// current window.
while (mp.has(A[i])) {
mp.delete(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
var A = [0, 1, 2, 3, 0, 1, 4];
var B = [9, 8, 1, 2, 3, 4, 5];
var n = A.length;
document.write( returnMaxSum(A, B, n));
// This code is contributed by importantly.
</script>
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.
Similar Reads
Rearrange an array to maximize sum of Bitwise AND of same-indexed elements with another array
Given two arrays A[] and B[] of sizes N, the task is to find the maximum sum of Bitwise AND of same-indexed elements in the arrays A[] and B[] that can be obtained by rearranging the array B[] in any order. Examples: Input: A[] = {1, 2, 3, 4}, B[] = {3, 4, 1, 2}Output: 10Explanation: One possible wa
15 min read
Find all unique pairs of maximum and second maximum elements over all sub-arrays in O(NlogN)
Let (a, b) represent the ordered pair of the second maximum and the maximum element of an array respectively. We need to find all such unique pairs overall contiguous sub-arrays of a given array. Examples: Input: Arr = [ 1, 2, 3, 4, 5 ] Output: (1, 2) (2, 3) (3, 4) (4, 5) Input: Arr = [ 1, 1, 2 ] Ou
13 min read
Break an array into maximum number of sub-arrays such that their averages are same
Given an integer array, the task is to divide the array into the maximum number of sub-arrays such that the averages of all subarrays are the same. If it is not possible to divide, then print "Not possible". Examples: Input : arr[] = {1, 5, 7, 2, 0}; Output : (0 1) (2 4) Subarrays arr[0..1] and arr[
8 min read
Smallest element with K set bits such that sum of Bitwise AND of each array element with K is maximum
Given an array arr[] consisting of N integers and integer K, the task is to find the smallest integer X with exactly K set bits such that the sum of Bitwise AND of X with every array element arr[i] is maximum. Examples: Input: arr[] = {3, 4, 5, 1}, K = 1Output: 4Explanation: Consider the value of X
8 min read
Sum of elements in 1st array such that number of elements less than or equal to them in 2nd array is maximum
Given two unsorted arrays arr1[] and arr2[], the task is to find the sum of elements of arr1[] such that the number of elements less than or equal to them in arr2[] is maximum. Examples: Input: arr1[] = {1, 2, 3, 4, 7, 9}, arr2[] = {0, 1, 2, 1, 1, 4} Output: 20 Below table shows the count of element
15 min read
Maximum elements that can be removed from front of two arrays such that their sum is at most K
Given an integer K and two arrays A[] and B[] consisting of N and M integers, the task is to maximize the number of elements that can be removed from the front of either array according to the following rules: Remove an element from the front of either array A[] and B[] such that the value of the re
15+ min read
Distribute given arrays into K sets such that total sum of maximum and minimum elements of all sets is maximum
Given two arrays, the first arr[] of size N and the second brr[] of size K. The task is to divide the first array arr[] into K sets such that the i-th set should contain brr[i] elements from the second array brr[], and the total sum of maximum and minimum elements of all sets is maximum. Examples: I
8 min read
Maximum number of elements from an array B[] that are present in ranges [A[i] + K, A[i] - K]
Given two arrays A[] of size N and B[] of size M and an integer K, the task is to select at most one element from array B[] for every element A[i] such that the element lies in the range [A[i] - K, A[i] + K] ( for 0 <= i <= N - 1 ). Print the maximum number of elements that can be selected fro
7 min read
Rearrange array elements to maximize the sum of MEX of all prefix arrays
Given an array arr[] of size N, the task is to rearrange the array elements such that the sum of MEX of all prefix arrays is the maximum possible. Note: MEX of a sequence is the minimum non-negative number not present in the sequence. Examples: Input: arr[] = {2, 0, 1}Output: 0, 1, 2Explanation:Sum
7 min read
Maximum sum by picking elements from two arrays in order | Set 2
Given two arrays A[] and B[], each of size N, and two integers X and Y denoting the maximum number of elements that can be picked from A[] and B[] respectively, the task is to find the maximum possible sum by selecting N elements in such a way that for any index i, either A[i] or B[i] can be chosen.
10 min read