Open In App

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

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, 22}
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:

Below is the implementation of the above approach:




// 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 through the array
    // Note that the array is traversed till high <= N
    // so that the corner case can be handled
    while (high <= N) {
      if(high==N){
        //Calculate the currSum for the subarray
        //after the last updated low to high-1
        currSum=0;
        for (int i = low; i <= high - 1;
                 i++)
                currSum += Y[i];
 
            // Find the maximum sum
            maxSum = max(maxSum, currSum);
        break;
      }
        // If the current element 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, 22 };
    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 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 through the array
    // Note that the array is traversed till high <= N
    // so that the corner case can be handled
    while (high <= N) {
      if(high==N){
           // Calculate the currSum for the subarray
        // after the last updated low to high-1
        currSum = 0;
        for (int i = low; i <= high - 1;i++)
             currSum += Y[i];
        // Find the maximum sum
        maxSum = Math.max(maxSum, currSum);
        break;
      }
      // If the current element 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, 22 };
    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.




# Python code for the above approach
 
# Function to find the max sum
def findMaxSumSubarray(X, Y, N):
 
    # Array to store the elements
    # and their indices
    m = [0] * (1001);
 
    # Initialize all elements as -1
    for i in range(1001):
        m[i] = -1;
 
    # low and high represent
    # beginning and end of subarray
    low = 0
    high = 0
    currSum = 0
    maxSum = 0;
 
    # Iterate through the array
    # Note that the array is traversed till high <= N
    # so that the corner case can be handled
    while (high <= N):
        if(high == N):
            currSum=0;
            # Calculate the currSum for the subarray
            # after the last updated low to high-1
            for i in range(low, high):
                currSum += Y[i];
            maxSum = max(maxSum, currSum);
            break;
     
        # If the current element already
        # exists in the current subarray
        if (m[X[high]] != -1 and m[X[high]] >= low):
            currSum = 0;
 
            # Calculate the sum
            # of current subarray
            for i in range(low, high):
                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 += 1
     
 
    # Return the maxSum
    return maxSum;
 
 
# Driver code
X = [0, 1, 2, 0, 2];
Y = [5, 6, 7, 8, 22];
N = len(X)
 
# Function call to find the sum
maxSum = findMaxSumSubarray(X, Y, N);
 
# Print the result
print(maxSum, end="")
 
# This code is contributed by Saurabh Jaiswal




// C# program for above approach
using System;
using System.Collections.Generic;
 
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 through the array
    // Note that the array is traversed till high <= N
    // so that the corner case can be handled
    while (high <= N)
    {
      if(high==N){
        // Calculate the currSum for the subarray
        // after the last updated low to high-1
        currSum=0;
        for (int i = low; i <= high - 1;
             i++)
          currSum += Y[i];
 
        // Find the maximum sum
        maxSum = Math.Max(maxSum, currSum);
        break;
      }
 
      // If the current element 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
  static public void Main ()
  {
 
    int[] X = { 0, 1, 2, 0, 2 };
    int[] Y = { 5, 6, 7, 8, 22 };
    int N = X.Length;
 
    // Function call to find the sum
    int maxSum = findMaxSumSubarray(X, Y, N);
 
    // Print the result
    Console.WriteLine(maxSum);
  }
}
 
// This code is contributed by hrithikgarg03188.




<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 through the array
           // Note that the array is traversed till high <= N
           // so that the corner case can be handled
           while (high <= N)
           {
               if(high==N){
               // Calculate the currSum for the subarray
               // after the last updated low to high-1
               currSum=0;
               for (let i = low; i <= high - 1;
                       i++)
                       currSum += Y[i];
 
                   // Find the maximum sum
                   maxSum = Math.max(maxSum, currSum);
                   break;
               }
               // If the current element 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, 22];
       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
30

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

 


Article Tags :