Open In App

Maximum Subarray Length with Divisibility and Sum Constraint

Last Updated : 11 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two integers N, K, and two arrays A and B each of size N, such that for every index i, A[i] lies between [1, 104] and B[i] lies between [1, 109]. Find the maximum subarray length [l, r] such that:

  • For each index i which lies between [l, r-1], B[i] is divisible by B[i+1] and
  • The sum of all the elements in the range [l, r] in array A <= K.

Examples:

Input: N = 5, A[] = {3, 2, 4, 1, 8}, B[] = {4, 4, 2, 4, 1}, K = 12
Output: 3
Explanation: A valid and max length subarray can be l = 0, r = 2.

Input: N = 4, A[] = {5, 4, 1, 2}, B[] = {6, 2, 3, 1}, K = 8
Output: 2
Explanation: A valid and max length subarray can be l = 2, r = 3.

Approach: To solve the problem follow the below idea:

The problem can be solved by maintaining a sliding window using two pointers. At every index, we will increase the length of the sliding window and check whether the conditions are getting fulfilled on both arrays A and B. If the divisibility check of subarray B fails, then it means that we need to start with a new sliding window from this index. If the sum of subarray A becomes greater than K, we start reducing the size of the window by moving the start pointer forward. After satisfying both the conditions, update the answer.

Steps to solve the problem:

  • Maintain 2 pointers, start and end to keep track of the sliding window.
  • Initialize the sum of subarray sum = 0.
  • Maintain a variable ans to keep track of the length of the longest valid sliding window encountered so far.
  • Increment the length of the sliding window by incrementing end by 1.
  • Check for the divisibility condition in subarray B:
    • If the divisibility check fails, start a new subarray from this index.
    • If the divisibility check passes, check if the sum of subarray A is less than K.
      • If sum <= K, update ans if the window’s length is greater than ans.
      • If sum > K, decrease the window’s length by moving the start pointer until we have sum <= K and then update ans if the window’s length is greater than ans.
  • After iterating over the whole array, return and.

Below is the implementation for the above approach:

C++




// C++ code for the above approach:
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the maximum
// valid subarray length
long maxLengthSubarray(int n, int a[], int b[], int k)
{
    // Two pointers to maintain a sliding window
    int start = 0, end;
 
    // Stores the sum of window
    int sum = 0;
 
    // Stores the maximum valid subarray length
    int ans = 0;
    for (end = 0; end < n; end++) {
 
        // Divisibility Check in array b,
        // start == end is to check if the element
        // is the first element of the subarray
        if (start == end || b[end - 1] % b[end] == 0) {
            sum += a[end];
 
            // Sum Check in array a,
            // Reduce the window size until
            // sum becomes less than k
            while (sum > k) {
                sum -= a[start++];
            }
            ans = max(ans, end - start + 1);
        }
        else {
 
            // If divisibility check fails start
            // a new window from this index
            start = end;
            end -= 1;
            sum = 0;
        }
    }
    return ans;
}
 
// Drivers code
int main()
{
    int n = 5, k = 12;
    int a[] = { 3, 2, 4, 1, 8 };
    int b[] = { 4, 4, 2, 4, 1 };
 
    // Function call
    cout << maxLengthSubarray(n, a, b, k) << '\n';
    return 0;
}


Java




// Java Code for the above approach:
 
import java.io.*;
import java.util.*;
 
public class GFG {
 
    // Function to calculate the maximum
    // valid subarray length
    public static long maxLengthSubarray(int n, int[] a,
                                         int[] b, int k)
    {
        // Two pointers to maintain a sliding window
        int start = 0, end;
        // stores the sum of window
        int sum = 0;
        // stores the maximum valid subarray length
        int ans = 0;
 
        for (end = 0; end < n; end++) {
            // Divisibility Check in array b,
            // start == end is to check if the element
            // is the first element of the subarray
            if (start == end || b[end - 1] % b[end] == 0) {
                sum += a[end];
                // Sum Check in array a,
                // Reduce the window size until
                // sum becomes less than k
                while (sum > k) {
                    sum -= a[start++];
                }
                ans = Math.max(ans, end - start + 1);
            }
            else {
                // If divisibility check fails start
                // a new window from this index
                start = end;
                end -= 1;
                sum = 0;
            }
        }
        return ans;
    }
 
    public static void main(String[] args)
    {
        int n = 5, k = 12;
        int[] a = { 3, 2, 4, 1, 8 };
        int[] b = { 4, 4, 2, 4, 1 };
 
        // Function call
        System.out.println(maxLengthSubarray(n, a, b, k));
    }
}


Python3




# Python Code for the above approach:
 
# Function to calculate the maximum
# valid subarray length
def max_length_common_subarray(n, a, b, k):
 
    # Two pointers to maintain a sliding window
    start = 0
    end = 0
    # Stores the sum of window
    window_sum = 0
    # Stores the maximum valid subarray length
    ans = 0
 
    for end in range(n):
        # Divisibility Check in array b,
        # start == end is to check if the element
        # is the first element of the subarray
        if start == end or b[end - 1] % b[end] == 0:
            window_sum += a[end]
            # Sum Check in array a,
            # Reduce the window size until
            # sum becomes less than k
            while window_sum > k:
                window_sum -= a[start]
                start += 1
            ans = max(ans, end - start + 1)
        else:
            # If divisibility check fails start
            # a new window from this index
            start = end
            end -= 1
            window_sum = 0
 
    return ans
 
 
n = 5
k = 12
a = [3, 2, 4, 1, 8]
b = [4, 4, 2, 4, 1]
 
# Function call
print(max_length_common_subarray(n, a, b, k))


C#




// C# Implementation
using System;
 
public class GFG
{
    // Function to calculate the maximum
    // valid subarray length
    public static long MaxLengthSubarray(int n, int[] a, int[] b, int k)
    {
        // Two pointers to maintain a sliding window
        int start = 0, end;
        // stores the sum of window
        int sum = 0;
        // stores the maximum valid subarray length
        int ans = 0;
 
        for (end = 0; end < n; end++)
        {
            // Divisibility Check in array b,
            // start == end is to check if the element
            // is the first element of the subarray
            if (start == end || b[end - 1] % b[end] == 0)
            {
                sum += a[end];
                // Sum Check in array a,
                // Reduce the window size until
                // sum becomes less than k
                while (sum > k)
                {
                    sum -= a[start++];
                }
                ans = Math.Max(ans, end - start + 1);
            }
            else
            {
                // If divisibility check fails start
                // a new window from this index
                start = end;
                end -= 1;
                sum = 0;
            }
        }
        return ans;
    }
 
    public static void Main(string[] args)
    {
        int n = 5, k = 12;
        int[] a = { 3, 2, 4, 1, 8 };
        int[] b = { 4, 4, 2, 4, 1 };
 
        // Function call
        Console.WriteLine(MaxLengthSubarray(n, a, b, k));
    }
}
 
// This code is contributed by Sakshi


Javascript




function maxLengthSubarray(n, a, b, k) {
    // Two pointers to maintain a sliding window
    let start = 0;
    let end = 0;
 
    // Stores the sum of the window
    let sum = 0;
 
    // Stores the maximum valid subarray length
    let ans = 0;
 
    for (end = 0; end < n; end++) {
        // Divisibility check in array b,
        // start == end is to check if the element
        // is the first element of the subarray
        if (start === end || b[end - 1] % b[end] === 0) {
            sum += a[end];
 
            // Sum check in array a,
            // Reduce the window size until
            // sum becomes less than k
            while (sum > k) {
                sum -= a[start++];
            }
 
            ans = Math.max(ans, end - start + 1);
        } else {
            // If divisibility check fails, start
            // a new window from this index
            start = end;
            end -= 1;
            sum = 0;
        }
    }
 
    return ans;
}
 
// Driver code
const n = 5;
const k = 12;
const a = [3, 2, 4, 1, 8];
const b = [4, 4, 2, 4, 1];
 
// Function call
console.log(maxLengthSubarray(n, a, b, k));


Output

3




Time Complexity: O(N), where N is the size of array A[] and B[]
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads