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.
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 subarrays of B. For every subarray, check if elements same subarray in A are distinct or not. If distinct, then compare sum with result and update result.
Time complexity of this solution is O(n2)
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.
Time complexity of this solution is O(n). 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 contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Sliding Window Maximum (Maximum of all subarrays of size k) using stack in O(n) time
- Sliding Window Maximum (Maximum of all subarrays of size k)
- Count distinct elements in every window of size k
- Sum of elements in 1st array such that number of elements less than or equal to them in 2nd array is maximum
- Unique element in an array where all elements occur k times except one
- Find all unique pairs of maximum and second maximum elements over all sub-arrays in O(NlogN)
- Maximum in array which is at-least twice of other elements
- Maximum value K such that array has at-least K elements that are >= K
- Maximum length of the sub-array whose first and last elements are same
- Find maximum xor of k elements in an array
- Covering maximum array elements with given value
- Maximum set bit sum in array without considering adjacent elements
- Maximum value after merging all elements in the array
- Maximum sum of all elements of array after performing given operations
- Maximum sum possible for a sub-sequence such that no two elements appear at a distance < K in the array