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
Maximum Sum SubArray using Divide and Conquer | Set 2 Given an array arr[] of integers, the task is to find the maximum sum sub-array among all the possible sub-arrays.Examples: Input: arr[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4} Output: 6 {4, -1, 2, 1} is the required sub-array.Input: arr[] = {2, 2, -2} Output: 4 Approach: Till now we are only aware of Kad
13 min read
C++ Program for Size of The Subarray With Maximum Sum An array is given, find length of the subarray having maximum sum. Examples : Input : a[] = {1, -2, 1, 1, -2, 1} Output : Length of the subarray is 2 Explanation: Subarray with consecutive elements and maximum sum will be {1, 1}. So length is 2 Input : ar[] = { -2, -3, 4, -1, -2, 1, 5, -3 } Output :
4 min read
Maximum length of subarray such that sum of the subarray is even Given an array of N elements. The task is to find the length of the longest subarray such that sum of the subarray is even.Examples: Input : N = 6, arr[] = {1, 2, 3, 2, 1, 4}Output : 5Explanation: In the example the subarray in range [2, 6] has sum 12 which is even, so the length is 5.Input : N = 4,
11 min read
Length of longest subarray for each index in Array where element at that index is largest Given an array arr[] of size N, the task is to calculate, for i(0<=i<N), the maximum length of a subarray containing arr[i], where arr[i] is the maximum element. Example: Input : arr[ ] = {62, 97, 49, 59, 54, 92, 21}, N=7Output: 1 7 1 3 1 5 1Explanation: The maximum length of subarray in which
15 min read
Sum of Max of Subarrays Given an array arr[], the task is to find the sum of the maximum elements of every possible non-empty sub-arrays of the given array arr[].Examples: Input: arr[] = [1, 3, 2]Output: 15Explanation: All possible non-empty subarrays of [1, 3, 2] are {1}, {3}, {2}, {1, 3}, {3, 2} and {1, 3, 2}. The maximu
12 min read
Find the maximum sum after dividing array A into M Subarrays Given a sorted array A[] of size N and an integer M. You need to divide the array A[] into M non-empty consecutive subarray (1 ? M ? N) of any size such that each element is present in exactly one of the M-subarray. After dividing the array A[] into M subarrays you need to calculate the sum [max(i)
10 min read
Longest Sub-array with maximum average value Given an array arr[] of n integers. The task is to find the maximum length of the sub-array which has the maximum average value (average of the elements of the sub-array). Examples: Input: arr[] = {2, 3, 4, 5, 6} Output: 1 {6} is the required sub-arrayInput: arr[] = {6, 1, 6, 6, 0} Output: 2 {6} and
6 min read
Length of longest sub-array with maximum arithmetic mean. Given an array of n-elements find the longest sub-array with the greatest arithmetic mean. The length of the sub-array must be greater than 1 and the mean should be calculated as an integer only.Examples: Input : arr[] = {3, 2, 1, 2} Output : 2 sub-array 3, 2 has greatest arithmetic mean Input :arr[
5 min read
Longest subarray having maximum sum Given an array arr[] containing n integers. The problem is to find the length of the subarray having maximum sum. If there exists two or more subarrays with maximum sum then print the length of the longest subarray.Examples: Input : arr[] = {5, -2, -1, 3, -4}Output : 4There are two subarrays with ma
12 min read
Maximum length of subarray with same sum at corresponding indices from two Arrays Given two arrays A[] and B[] both consisting of N integers, the task is to find the maximum length of subarray [i, j] such that the sum of A[i... j] is equal to B[i... j]. Examples: Input: A[] = {1, 1, 0, 1}, B[] = {0, 1, 1, 0}Output: 3Explanation: For (i, j) = (0, 2), sum of A[0... 2] = sum of B[0.
6 min read