VOOZH about

URL: https://www.geeksforgeeks.org/dsa/optimizing-range-selection-for-maximum-sum-of-b/

⇱ Optimizing Range Selection for Maximum Sum of B[] - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Optimizing Range Selection for Maximum Sum of B[]

Last Updated : 23 Jul, 2025

Given two arrays A[] and B[] of length N. Then your task is to choose a range [L, R] in such a way that both the conditions are met, Then the task is to output the Maximum possible sum of such B[L, R].

  • A[L, R] contains unique elements.
  • Sum of B[L, R] is the maximum possible.

Examples:

Input: N = 5, A[] = {0, 1, 2, 0, 2}, B[] = {5, 6, 7, 8, 2}
Output: 21
Explanation: If we took the range [L, R] as [2, 4]. It gives A[2, 4] = {1, 2, 0} and B[2, 4] = {6, 7, 8}. The sum of B[2, 4] is 6+7+8 = 21. All the elements of A[2, 4] are unique and B[2, 4] is maximum 21. Both the conditions are satisfied. Therefore, output is 21.

Input: N = 3, A[] = {1, 1, 1}, B[] = {3, 4, 5}
Output: 5
Explanation: If we took range [L, R] as [3, 3]. It gives A[3, 3] = {1} and B[3, 3] = {5}. Then sum of B[3, 3] is 5. which is maximum possible according to the given constraints. Therefore, output is 5.

Approach: Implement the idea below to solve the problem

The problem is observation based and can be implemented easily. The problem requires using HashSet Data - Structure.

Steps were taken to solve the problem:

  • Create a HashSet let say Set to store the unique elements.
  • Declare three variables let say J, Sum and Max, initialize them all equal to 0.
  • Run a loop for i = 0 to i < N and follow below mentioned steps under the scope of loop:
    • Num = A[i]
    • If (Set is Empty)
      • Add Num into Set
      • Add B[i] into Sum
    • Else
      • If (Set not contains Num)
        • Add num into Set
        • Add B[i] into Sum
      • Else
        • While (A[j] != Num)
          • Remove A[j] from Set
          • Sum -= B[j]
          • Increment J
        • Subtract B[j] from Sum
        • Increment j
        • Sum += B[i]
      • Update Max with Sum if Sum is greater than Max.
  • Output the value stored in Max.

Code to implement the approach:


Output
21

Time Complexity: O(N)
Auxiliary space: O(N), As HashSet is used to store unique elements.

Comment