Longest unique subarray of an Array with maximum sum in another Array
Last Updated :
11 Feb, 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, 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:
- 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.
- Note that you will be encountering a corner case which can result in wrong answer, for instance, let's consider our first Input, then the subarray {8, 2} is the right choice and 30 is our right answer. So handle that corner case separately by summing all elements from the previous low to 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 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
// 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.
Python3
# 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#
// 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.
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 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>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
C++ Programming Language
C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read