Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Longest unique subarray of an Array with maximum sum in another Array

  • Difficulty Level : Medium
  • Last Updated : 20 Jan, 2022

Given two arrays X[] and Y[] of size N, the task is to find the longest subarray in X[] containing only unique values such that a subarray with similar indices in Y[] should have a maximum sum. The value of array elements is in the range [0, 1000].

Examples:

Input: N = 5,  
X[] = {0, 1, 2, 0, 2},  
Y[] = {5, 6, 7, 8, 2}
Output: 21
Explanation: The largest unique subarray in X[] with maximum sum in Y[] is {1, 2, 0}. 
So, the subarray with same indices in Y[] is {6, 7, 8}.
Therefore maximum sum is 21.

Input: N = 3,  
X[] = {1, 1, 1},  
Y[] = {2, 6, 7}
Output: 7

 

Naive Approach: The task can be solved by generating all the subarrays of the array X[], checking for each subarray if it is valid, and then calculating the sum in the array for corresponding indices in Y.

Time Complexity: O(N3)
Auxiliary Space: O(N)

Efficient Approach: The task can be solved using the concept of the sliding window. Follow the below steps to solve the problem:

  • Create an array m of size 1001 and initialize all elements as -1. For index i, m[i] stores the index at which i is present in the subarray. If m[i] is -1, it means the element doesn’t exist in the subarray.
  • Initialize low = 0, high = 0, these two pointers will define the indices of the current subarray.
  • currSum and maxSum, define the sum of the current subarray and the maximum sum in the array.
  • Iterate over a loop and check if the current element at index high exists in the subarray already, if it does find the sum of elements in the subarray, update maxSum (if needed) and update low. Now, finally, move to the next element by incrementing high.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the max sum
int findMaxSumSubarray(int X[], int Y[],
                       int N)
{
    // Array to store the elements
    // and their indices
    int m[1001];
 
    // Initialize all elements as -1
    for (int i = 0; i < 1001; i++)
        m[i] = -1;
 
    // low and high represent
    // beginning and end of subarray
    int low = 0, high = 0;
    int currSum = 0, maxSum = 0;
 
    // Iterate throught the array
    while (high < N) {
        // If the current elemetn already
        // exists in the current subarray
        if (m[X[high]] != -1
            && m[X[high]] >= low) {
            currSum = 0;
 
            // Calculate the sum
            // of current subarray
            for (int i = low; i <= high - 1;
                 i++)
                currSum += Y[i];
 
            // Find the maximum sum
            maxSum = max(maxSum, currSum);
 
            // Starting index of new subarray
            low = m[X[high]] + 1;
        }
 
        // Keep expanding the subarray
        // and mark the index
        m[X[high]] = high;
        high++;
    }
 
    // Return the maxSum
    return maxSum;
}
 
// Driver code
int main()
{
    int X[] = { 0, 1, 2, 0, 2 };
    int Y[] = { 5, 6, 7, 8, 2 };
    int N = sizeof(X) / sizeof(X[0]);
 
    // Function call to find the sum
    int maxSum = findMaxSumSubarray(X, Y, N);
 
    // Print the result
    cout << maxSum << endl;
    return 0;
}

Java




// Java program for the above approach
import java.util.*;
public class GFG
{
 
  // Function to find the max sum
  static int findMaxSumSubarray(int X[], int Y[],
                                int N)
  {
 
    // Array to store the elements
    // and their indices
    int m[] = new int[1001];
 
    // Initialize all elements as -1
    for (int i = 0; i < 1001; i++)
      m[i] = -1;
 
    // low and high represent
    // beginning and end of subarray
    int low = 0, high = 0;
    int currSum = 0, maxSum = 0;
 
    // Iterate throught the array
    while (high < N) {
      // If the current elemetn already
      // exists in the current subarray
      if (m[X[high]] != -1
          && m[X[high]] >= low) {
        currSum = 0;
 
        // Calculate the sum
        // of current subarray
        for (int i = low; i <= high - 1;
             i++)
          currSum += Y[i];
 
        // Find the maximum sum
        maxSum = Math.max(maxSum, currSum);
 
        // Starting index of new subarray
        low = m[X[high]] + 1;
      }
 
      // Keep expanding the subarray
      // and mark the index
      m[X[high]] = high;
      high++;
    }
 
    // Return the maxSum
    return maxSum;
  }
 
  // Driver code
  public static void main(String args[])
  {
    int X[] = { 0, 1, 2, 0, 2 };
    int Y[] = { 5, 6, 7, 8, 2 };
    int N = X.length;
 
    // Function call to find the sum
    int maxSum = findMaxSumSubarray(X, Y, N);
 
    // Print the result
    System.out.println(maxSum);
  }
}
 
// This code is contributed by Samim Hossain Mondal.

Javascript




<script>
       // JavaScript code for the above approach
 
       // Function to find the max sum
       function findMaxSumSubarray(X, Y, N)
       {
        
           // Array to store the elements
           // and their indices
           let m = new Array(1001);
 
           // Initialize all elements as -1
           for (let i = 0; i < 1001; i++)
               m[i] = -1;
 
           // low and high represent
           // beginning and end of subarray
           let low = 0, high = 0;
           let currSum = 0, maxSum = 0;
 
           // Iterate throught the array
           while (high < N)
           {
            
               // If the current elemetn already
               // exists in the current subarray
               if (m[X[high]] != -1
                   && m[X[high]] >= low) {
                   currSum = 0;
 
                   // Calculate the sum
                   // of current subarray
                   for (let i = low; i <= high - 1;
                       i++)
                       currSum += Y[i];
 
                   // Find the maximum sum
                   maxSum = Math.max(maxSum, currSum);
 
                   // Starting index of new subarray
                   low = m[X[high]] + 1;
               }
 
               // Keep expanding the subarray
               // and mark the index
               m[X[high]] = high;
               high++;
           }
 
           // Return the maxSum
           return maxSum;
       }
 
       // Driver code
       let X = [0, 1, 2, 0, 2];
       let Y = [5, 6, 7, 8, 2];
       let N = X.length
 
       // Function call to find the sum
       let maxSum = findMaxSumSubarray(X, Y, N);
 
       // Print the result
       document.write(maxSum + '<br>')
 
        // This code is contributed by Potta Lokesh
   </script>

 
 

Output
21

 

Time Complexity: O(N)
Auxiliary Space: O(N)

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!