Maximum length of subarray with same sum at corresponding indices from two Arrays
Last Updated :
04 Sep, 2022
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: 3
Explanation: For (i, j) = (0, 2), sum of A[0... 2] = sum of B[0... 2] (i.e, A[0]+A[1]+A[2] = B[0]+B[1]+B[2] => 1+1+0 = 0+1+1 => 2 = 2). Similarly, for (i, j) = (1, 3), sum of A[1... 3] = B[1... 3]. Therefore, the length of the subarray with equal sum is 3 which is the maximum possible.
Input: A[] = {1, 2, 3, 4}, B[] = {4, 3, 2, 1}
Output: 4
Approach: The given problem can be solved by using a Greedy Approach with the help of unordered maps. It can be observed that for a pair (i, j), if the sum of A[i... j] = sum of B[i... j], then \sum_{x=i}^{j} (A[x] - B[x]) = 0 must hold true. Therefore, a prefix sum array of the difference (A[x] - B[x]) can be created. It can be observed that the repeated values in the prefix sum array represent that the sum of a subarray between the two repeated values must be 0. Hence, keep a track of the maximum size of such subarrays in a variable maxSize which will be the required answer.
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 maximum length of subarray
// of array A and B having equal sum
int maxLength(vector<int>& A, vector<int>& B)
{
int n = A.size();
// Stores the maximum size of valid subarray
int maxSize = 0;
// Stores the prefix sum of the difference
// of the given arrays
unordered_map<int, int> pre;
int diff = 0;
pre[0] = 0;
// Traverse the given array
for (int i = 0; i < n; i++) {
// Add the difference of the
// corresponding array element
diff += (A[i] - B[i]);
// If current difference is not present
if (pre.find(diff) == pre.end()) {
pre[diff] = i + 1;
}
// If current difference is present,
// update the value of maxSize
else {
maxSize = max(maxSize, i - pre[diff] + 1);
}
}
// Return the maximum length
return maxSize;
}
// Driver Code
int main()
{
vector<int> A = { 1, 2, 3, 4 };
vector<int> B = { 4, 3, 2, 1 };
cout << maxLength(A, B);
return 0;
}
Java
// Java program for the above approach
import java.util.HashMap;
class GFG {
// Function to find maximum length of subarray
// of array A and B having equal sum
public static int maxLength(int[] A, int[] B) {
int n = A.length;
// Stores the maximum size of valid subarray
int maxSize = 0;
// Stores the prefix sum of the difference
// of the given arrays
HashMap<Integer, Integer> pre = new HashMap<Integer, Integer>();
int diff = 0;
pre.put(0, 0);
// Traverse the given array
for (int i = 0; i < n; i++) {
// Add the difference of the
// corresponding array element
diff += (A[i] - B[i]);
// If current difference is not present
if (!pre.containsKey(diff)) {
pre.put(diff, i + 1);
}
// If current difference is present,
// update the value of maxSize
else {
maxSize = Math.max(maxSize, i - pre.get(diff) + 1);
}
}
// Return the maximum length
return maxSize;
}
// Driver Code
public static void main(String args[]) {
int[] A = { 1, 2, 3, 4 };
int[] B = { 4, 3, 2, 1 };
System.out.println(maxLength(A, B));
}
}
// This code is contributed by gfgking.
Python3
# python program for the above approach
# Function to find maximum length of subarray
# of array A and B having equal sum
def maxLength(A, B):
n = len(A)
# Stores the maximum size of valid subarray
maxSize = 0
# Stores the prefix sum of the difference
# of the given arrays
pre = {}
diff = 0
pre[0] = 0
# Traverse the given array
for i in range(0, n):
# Add the difference of the
# corresponding array element
diff += (A[i] - B[i])
# If current difference is not present
if (not (diff in pre)):
pre[diff] = i + 1
# If current difference is present,
# update the value of maxSize
else:
maxSize = max(maxSize, i - pre[diff] + 1)
# Return the maximum length
return maxSize
# Driver Code
if __name__ == "__main__":
A = [1, 2, 3, 4]
B = [4, 3, 2, 1]
print(maxLength(A, B))
# This code is contributed by rakeshsahni
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to find maximum length of subarray
// of array A and B having equal sum
public static int maxLength(int[] A, int[] B) {
int n = A.Length;
// Stores the maximum size of valid subarray
int maxSize = 0;
// Stores the prefix sum of the difference
// of the given arrays
Dictionary<int, int> pre =
new Dictionary<int, int>();
int diff = 0;
pre.Add(0, 0);
// Traverse the given array
for (int i = 0; i < n; i++) {
// Add the difference of the
// corresponding array element
diff += (A[i] - B[i]);
// If current difference is not present
if (!pre.ContainsKey(diff)) {
pre.Add(diff, i + 1);
}
// If current difference is present,
// update the value of maxSize
else {
maxSize = Math.Max(maxSize, i - pre[(diff)] + 1);
}
}
// Return the maximum length
return maxSize;
}
// Driver Code
public static void Main()
{
int[] A = { 1, 2, 3, 4 };
int[] B = { 4, 3, 2, 1 };
Console.Write(maxLength(A, B));
}
}
// This code is contributed by sanjoy_62.
JavaScript
<script>
// JavaScript program for the above approach
// Function to find maximum length of subarray
// of array A and B having equal sum
const maxLength = (A, B) => {
let n = A.length;
// Stores the maximum size of valid subarray
let maxSize = 0;
// Stores the prefix sum of the difference
// of the given arrays
let pre = {};
let diff = 0;
pre[0] = 0;
// Traverse the given array
for (let i = 0; i < n; i++) {
// Add the difference of the
// corresponding array element
diff += (A[i] - B[i]);
// If current difference is not present
if (!(diff in pre)) {
pre[diff] = i + 1;
}
// If current difference is present,
// update the value of maxSize
else {
maxSize = Math.max(maxSize, i - pre[diff] + 1);
}
}
// Return the maximum length
return maxSize;
}
// Driver Code
let A = [1, 2, 3, 4];
let B = [4, 3, 2, 1];
document.write(maxLength(A, B));
// This code is contributed by rakeshsahni.
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Maximum length of same indexed subarrays from two given arrays satisfying the given condition Given two arrays arr[] and brr[] and an integer C, the task is to find the maximum possible length, say K, of the same indexed subarrays such that the sum of the maximum element in the K-length subarray in brr[] with the product between K and sum of the K-length subarray in arr[] does not exceed C.
15+ min read
Find Sum of pair from two arrays with maximum sum Given two arrays of positive and distinct integers. The task is to find a pair from the two arrays with maximum sum. Note: The pair should contain one element from both the arrays. Examples: Input : arr1[] = {1, 2, 3}, arr2[] = {4, 5, 6} Output : Max Sum = 9 Pair (3, 6) has the maximum sum. Input :
6 min read
Maximum sum of K-length subarray consisting of same number of distinct elements as the given array Given an array arr[] consisting of N integers and an integer K, the task is to find a subarray of size K with maximum sum and count of distinct elements same as that of the original array. Examples: Input: arr[] = {7, 7, 2, 4, 2, 7, 4, 6, 6, 6}, K = 6Output: 31Explanation: The given array consists o
15+ min read
Maximize sum of products at corresponding indices in two arrays by reversing at most one subarray in first Array Given two arrays A and B of size N, the task is to maximize the sum of A[i]*B[i] across all values of i from 0 to N-1 by reversing at most one subarray of array A. Examples: Input: N = 4, A = [5, 1, 2, 3], B = [1, 4, 3, 2]Output: 33Explanation: Array A after reversing the subarray A[0, 1] will becom
15 min read
Maximum OR sum of sub-arrays of two different arrays Given two arrays of positive integers. Select two sub-arrays of equal size from each array and calculate maximum possible OR sum of the two sub-arrays. Note: Let f(x, l, r) is the OR sum of all the elements in the range [l, r] in array x. Examples : Input : A[] = {1, 2, 4, 3, 2} B[] = {2, 3, 3, 12,
5 min read
Maximize sum of product of same-indexed elements of equal length subarrays obtained from two given arrays Given two arrays arr[] and brr[] of size N and M integers respectively, the task is to maximize the sum of the product of the same-indexed elements of two subarrays of an equal length with the selected subarray from the array brr[] being reversed. Examples: Input: arr[] = {-1, 3, -2, 4, 5}, brr[] =
13 min read
Maximum length of subarray consisting of same type of element on both halves of sub-array Given an array arr[] of N integers, the task is to find the maximum length of sub-array consisting of the same type of element on both halves of the sub-array. Also, the elements on both halves differ from each other. Examples: Input: arr[] = {2, 3, 4, 4, 5, 5, 6, 7, 8, 10}Output: 4Explanation:{2, 3
8 min read
Maximize non decreasing Array size by replacing Subarray with sum Given an array arr[] of size N. In one operation only one subarray can be selected and replaced with the sum of the subarray. The task is to find the maximum size of the array after making it non-decreasing.Examples:Input: N = 5, arr[] = {5, 1, 6, 6, 6}Output: 4Explanation: maximum size non-decreasi
15+ min read
Longest Span with same Sum in two Binary arrays Given two binary arrays, a1[] and a2[] of the same size n. Find the length of the longest common span (i, j) where j >= i such that a1[i] + a1[i+1] + .... + a1[j] = a2[i] + a2[i+1] + .... + a2[j].Examples: Input: a1[] = [0, 1, 0, 0, 0, 0] a2[] = [1, 0, 1, 0, 0, 1] Output: 4 Explanation: The longe
14 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