The Wayback Machine - https://web.archive.org/web/20240818163946/https://www.geeksforgeeks.org/longest-subarray-sum-divisible-k/
Open In App

Longest subarray with sum divisible by K

Last Updated : 02 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an arr[] containing n integers and a positive integer k. The problem is to find the longest subarray’s length with the sum of the elements divisible by the given value k.

Examples:

Input: arr[] = {2, 7, 6, 1, 4, 5}, k = 3
Output: 4
Explanation: The subarray is {7, 6, 1, 4} with sum 18, which is divisible by 3.

Input: arr[] = {-2, 2, -5, 12, -11, -1, 7}, k = 3
Output: 5

Method 1 (Naive Approach): Consider all the subarrays and return the length of the subarray with a sum divisible by k that has the longest length. 

C++




// C++ implementation to find the longest subarray
// with sum divisible by k
 
#include <bits/stdc++.h>
using namespace std;
 
// function to find the longest subarray
// with sum divisible by k
 
int longestSubarrWthSumDivByK(int arr[], int N, int k)
{
         int maxl=0;
        for(int i=0;i<N;i++)
        {
            int sum1 = 0;
            for(int j=i;j<N;j++)
            {
                sum1+=arr[j];
                if(sum1 % k == 0)
                {
                    maxl = max(maxl , j - i + 1);
                }
                 
            }
        }
 
        return maxl;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 7, 6, 1, 4, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
 
    cout << "Length = "
         << longestSubarrWthSumDivByK(arr, n, k);
 
    return 0;
}
 
// This code is contributed by Arpit Jain


Java




import java.util.*;
 
class GFG {
 
  // function to find the longest subarray
  // with sum divisible by k
  static int longestSubarrWthSumDivByK(int arr[], int N, int k)
  {
    int maxl = 0;
    for (int i = 0; i < N; i++) {
      int sum1 = 0;
      for (int j = i; j < N; j++) {
        sum1 += arr[j];
        if (sum1 % k == 0)
          maxl = Math.max(maxl, j - i + 1);
      }
    }
 
    return maxl;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int arr[] = { 2, 7, 6, 1, 4, 5 };
    int n = arr.length;
    int k = 3;
 
    System.out.println("Length = "
                       + longestSubarrWthSumDivByK(arr, n, k));
  }
}
 
// This code is contributed by Ajax


C#




// C# implementation to find the longest subarray
// with sum divisible by k
 
using System;
 
class GFG {
 
    // function to find the longest subarray
    // with sum divisible by k
    static int longestSubarrWthSumDivByK(int[] arr, int N,
                                         int k)
    {
        int maxl = 0;
        for (int i = 0; i < N; i++) {
            int sum1 = 0;
            for (int j = i; j < N; j++) {
                sum1 += arr[j];
                if (sum1 % k == 0)
                    maxl = Math.Max(maxl, j - i + 1);
            }
        }
 
        return maxl;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        int[] arr = { 2, 7, 6, 1, 4, 5 };
        int n = arr.Length;
        int k = 3;
 
        Console.WriteLine(
            "Length = "
            + longestSubarrWthSumDivByK(arr, n, k));
    }
}
 
// This code is contributed by Karandeep1234


Python3




# Python3 implementation to find the longest subarray
# with sum divisible by k
 
def longestSubarrWthSumDivByK(arr, N, k):
    maxl = 0
    for i in range(N):
        sum1 = 0
        for j in range(i, N):
            sum1 += arr[j]
            if sum1 % k == 0:
                maxl = max(maxl, j - i + 1)
    return maxl
 
# Driver code
arr = [2, 7, 6, 1, 4, 5]
n = len(arr)
k = 3
 
print("Length =", longestSubarrWthSumDivByK(arr, n, k))


Javascript




// JavaScript implementation to find the longest subarray
// with sum divisible by k
function longestSubarrWthSumDivByK(arr, N, k) {
    let maxl = 0;
    for (let i = 0; i < N; i++) {
        let sum1 = 0;
        for (let j = i; j < N; j++) {
            sum1 += arr[j];
            if (sum1 % k === 0) {
                maxl = Math.max(maxl, j - i + 1);
            }
        }
    }
    return maxl;
}
 
// Driver code
let arr = [ 2, 7, 6, 1, 4, 5 ];
let N = arr.length;
let k = 3;
console.log("Length = " + longestSubarrWthSumDivByK(arr, N, k));
 
//This code is contributed by dhanshri borse


Output

Length = 4

Time Complexity: O(n2).
Auxiliary Space: O(1)

Method 2 (Efficient Approach): Create an array mod_arr[] where mod_arr[i] stores (sum(arr[0]+arr[1]..+arr[i]) % k). Create a hash table having tuple as (ele, i), where ele represents an element of mod_arr[] and i represents the element’s index of first occurrence in mod_arr[]. Now, traverse mod_arr[] from i = 0 to n and follow the steps given below.

  1. If mod_arr[i] == 0, then update max_len = (i + 1).
  2. Else if mod_arr[i] is not present in the hash table, then create tuple (mod_arr[i], i) in the hash table.
  3. Else, get the hash table’s value associated with mod_arr[i]. Let this be i.
  4. If maxLen < (i – idx), then update max_len = (i – idx).
  5. Finally, return max_len.

Below is the implementation of the above approach:

C++




// C++ implementation to find the longest subarray
// with sum divisible by k
 
#include <bits/stdc++.h>
using namespace std;
 
// function to find the longest subarray
// with sum divisible by k
 
int longestSubarrWthSumDivByK(int arr[], int n, int k)
{
    // unordered map 'um' implemented as
    // hash table
    unordered_map<int, int> um;
 
    // 'mod_arr[i]' stores (sum[0..i] % k)
    int mod_arr[n], max_len = 0;
    int curr_sum = 0;
 
    // traverse arr[] and build up the
    // array 'mod_arr[]'
    for (int i = 0; i < n; i++) {
        curr_sum += arr[i];
 
        // as the sum can be negative, taking modulo twice
        mod_arr[i] = ((curr_sum % k) + k) % k;
 
        // if true then sum(0..i) is divisible by k
        if (mod_arr[i] == 0)
            // update 'max'
            max_len = i + 1;
 
        // if value 'mod_arr[i]' not present in 'um'
        // then store it in 'um' with index of its
        // first occurrence
        else if (um.find(mod_arr[i]) == um.end())
            um[mod_arr[i]] = i;
 
        else
            // if true, then update 'max'
            if (max_len < (i - um[mod_arr[i]]))
            max_len = i - um[mod_arr[i]];
    }
 
    // return the required length of longest subarray
    // with sum divisible by 'k'
    return max_len;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 7, 6, 1, 4, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
 
    cout << "Length = "
         << longestSubarrWthSumDivByK(arr, n, k);
 
    return 0;
}
 
// Code updated by Kshitij Dwivedi


Java




// Java implementation to find the longest
// subarray with sum divisible by k
import java.io.*;
import java.util.*;
 
class GfG {
 
    // function to find the longest subarray
    // with sum divisible by k
    static int longestSubarrWthSumDivByK(int arr[], int n,
                                         int k)
    {
        // unordered map 'um' implemented as
        // hash table
        HashMap<Integer, Integer> um
            = new HashMap<Integer, Integer>();
 
        // 'mod_arr[i]' stores (sum[0..i] % k)
        int mod_arr[] = new int[n];
        int max_len = 0;
        int curr_sum = 0;
 
        // traverse arr[] and build up the
        // array 'mod_arr[]'
        for (int i = 0; i < n; i++) {
            curr_sum += arr[i];
 
            // as the sum can be negative,
            // taking modulo twice
            mod_arr[i] = ((curr_sum % k) + k) % k;
 
            // if true then sum(0..i) is
            // divisible by k
            if (mod_arr[i] == 0)
                // update 'max'
                max_len = i + 1;
 
            // if value 'mod_arr[i]' not present in 'um'
            // then store it in 'um' with index of its
            // first occurrence
            else if (um.containsKey(mod_arr[i]) == false)
                um.put(mod_arr[i], i);
 
            else
                // if true, then update 'max'
                if (max_len < (i - um.get(mod_arr[i])))
                max_len = i - um.get(mod_arr[i]);
        }
 
        // return the required length of longest subarray
        // with sum divisible by 'k'
        return max_len;
    }
 
    public static void main(String[] args)
    {
        int arr[] = { 2, 7, 6, 1, 4, 5 };
        int n = arr.length;
        int k = 3;
 
        System.out.println(
            "Length = "
            + longestSubarrWthSumDivByK(arr, n, k));
    }
}
 
// This code is contributed by Gitanjali, updated by Kshitij
// Dwivedi


Python3




# Python3 implementation to find the
# longest subarray with sum divisible by k
 
# Function to find the longest
# subarray with sum divisible by k
 
 
def longestSubarrWthSumDivByK(arr, n, k):
 
    # unordered map 'um' implemented
    # as hash table
    um = {}
 
    # 'mod_arr[i]' stores (sum[0..i] % k)
    mod_arr = [0 for i in range(n)]
    max_len = 0
    curr_sum = 0
 
    # Traverse arr[] and build up
    # the array 'mod_arr[]'
    for i in range(n):
        curr_sum += arr[i]
 
        # As the sum can be negative,
        # taking modulo twice
        mod_arr[i] = ((curr_sum % k) + k) % k
 
        # If true then sum(0..i) is
        # divisible by k
        if (mod_arr[i] == 0):
 
            # Update 'max_len'
            max_len = i + 1
 
        # If value 'mod_arr[i]' not present in
        # 'um' then store it in 'um' with index
        # of its first occurrence
        elif (mod_arr[i] not in um):
            um[mod_arr[i]] = i
 
        else:
              # If true, then update 'max_len'
            if (max_len < (i - um[mod_arr[i]])):
                max_len = i - um[mod_arr[i]]
 
    # Return the required length of longest subarray
    # with sum divisible by 'k'
    return max_len
 
 
# Driver Code
if __name__ == '__main__':
 
    arr = [2, 7, 6, 1, 4, 5]
    n = len(arr)
    k = 3
 
    print("Length =",
          longestSubarrWthSumDivByK(arr, n, k))
 
# This code is contributed by Surendra_Gangwar, updated by Kshitij Dwivedi


C#




using System;
using System.Collections.Generic;
 
// C# implementation to find the longest
// subarray with sum divisible by k
 
public class GfG {
 
    // function to find the longest subarray
    // with sum divisible by k
    public static int
    longestSubarrWthSumDivByK(int[] arr, int n, int k)
    {
        // unordered map 'um' implemented as
        // hash table
        Dictionary<int, int> um
            = new Dictionary<int, int>();
 
        // 'mod_arr[i]' stores (sum[0..i] % k)
        int[] mod_arr = new int[n];
        int max_len = 0;
        int curr_sum = 0;
 
        // traverse arr[] and build up the
        // array 'mod_arr[]'
        for (int i = 0; i < n; i++) {
            curr_sum += arr[i];
 
            // as the sum can be negative,
            // adjusting and calculating modulo twice
            mod_arr[i] = ((curr_sum % k) + k) % k;
 
            // if true then sum(0..i) is
            // divisible by k
            if (mod_arr[i] == 0) {
                // update 'max_len'
                max_len = i + 1;
            }
 
            // if value 'mod_arr[i]' not present in 'um'
            // then store it in 'um' with index of its
            // first occurrence
            else if (um.ContainsKey(mod_arr[i]) == false) {
                um[mod_arr[i]] = i;
            }
 
            else {
                // if true, then update 'max_len'
                if (max_len < (i - um[mod_arr[i]])) {
                    max_len = i - um[mod_arr[i]];
                }
            }
        }
 
        // return the required length of longest subarray
        // with sum divisible by 'k'
        return max_len;
    }
 
    public static void Main(string[] args)
    {
        int[] arr = new int[] { 2, 7, 6, 1, 4, 5 };
        int n = arr.Length;
        int k = 3;
 
        Console.WriteLine(
            "Length = "
            + longestSubarrWthSumDivByK(arr, n, k));
    }
}
 
// This code is contributed by Shrikant13, updated by
// Kshitij Dwivedi


Javascript




<script>
 
// Javascript implementation to find the longest subarray
// with sum divisible by k
 
// function to find the longest subarray
// with sum divisible by k
function longestSubarrWthSumDivByK(arr, n, k)
{
    // unordered map 'um' implemented as
    // hash table
    var um = new Map();
     
    // 'mod_arr[i]' stores (sum[0..i] % k)
    var mod_arr = Array(n), max_len = 0;
    var curr_sum = 0;
     
    // traverse arr[] and build up the
    // array 'mod_arr[]'
    for (var i = 0; i < n; i++)
    {
        curr_sum += arr[i];
         
        // as the sum can be negative, taking modulo twice
        mod_arr[i] = ((curr_sum % k) + k) % k;       
 
        // if true then sum(0..i) is divisible
        // by k
        if (mod_arr[i] == 0)
            // update 'max_len'
            max_len = i + 1;
         
        // if value 'mod_arr[i]' not present in 'um'
        // then store it in 'um' with index of its
        // first occurrence       
        else if (!um.has(mod_arr[i]))
            um.set(mod_arr[i] , i);
             
        else
            // if true, then update 'max_len'
            if (max_len < (i - um.get(mod_arr[i])))
                max_len = i - um.get(mod_arr[i]);           
    }
     
    // return the required length of longest subarray with
    // sum divisible by 'k'
    return max_len;
}                         
 
// Driver program to test above
var arr = [2, 7, 6, 1, 4, 5];
var n = arr.length;
var k = 3;
 
document.write( "Length = "
     + longestSubarrWthSumDivByK(arr, n, k));
      
// This code is contributed by rrrtnx, and updated by Kshitij Dwivedi
</script>


Output

Length = 4

Time Complexity: O(n), as we traverse the input array only once.
Auxiliary Space: O(n  + k), O(n) for mod_arr[], and O(k) for storing the remainder values in the hash table.

Space Optimized approach: The space optimization for the above approach to O(n) Instead of keeping a separate array to store the modulus of all values, we compute it on the go and store remainders in the hash table.

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
 
using namespace std;
 
// function to find the longest subarray
// with sum divisible by k
int longestSubarrWthSumDivByK(int arr[], int n, int k)
{
    // unordered map 'um' implemented as
    // hash table
    unordered_map<int, int> um;
 
    int max_len = 0;
    int curr_sum = 0;
 
    for (int i = 0; i < n; i++) {
        curr_sum += arr[i];
 
        int mod = ((curr_sum % k) + k) % k;
 
        // if true then sum(0..i) is divisible
        // by k
        if (mod == 0)
            // update 'max_len'
            max_len = i + 1;
 
        // if value 'mod_arr[i]' not present in 'um'
        // then store it in 'um' with index of its
        // first occurrence
        else if (um.find(mod) == um.end())
            um[mod] = i;
 
        else
            // if true, then update 'max_len'
            if (max_len < (i - um[mod]))
            max_len = i - um[mod];
    }
 
    // return the required length of longest subarray with
    // sum divisible by 'k'
    return max_len;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 7, 6, 1, 4, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
 
    cout << "Length = "
         << longestSubarrWthSumDivByK(arr, n, k);
 
    return 0;
}
 
// Code Updated by Kshitij Dwivedi


Java




/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
 
class GFG {
    static int longestSubarrWthSumDivByK(int arr[], int n,
                                         int k)
    {
        Map<Integer, Integer> map = new HashMap<>();
 
        int max_len = 0;
        int sum = 0;
 
        for (int i = 0; i < n; i++) {
            sum += arr[i];
 
            // to handle negative values as well
            int mod = ((sum % k) + k) % k;
 
            if (mod == 0)
                max_len = i + 1;
 
            if (!map.containsKey(mod))
                map.put(mod, i);
            else {
                int sz = i - map.get(mod);
                max_len = Math.max(max_len, sz);
            }
        }
 
        return max_len;
    }
 
    public static void main(String[] args)
    {
        int arr[] = { 2, 7, 6, 1, 4, 5 };
        int n = arr.length;
        int k = 3;
 
        System.out.println(
            "Length = "
            + longestSubarrWthSumDivByK(arr, n, k));
    }
}
 
// Updated By Kshitij Dwivedi


Python3




# function to find the longest subarray
#  with sum divisible by k
 
 
def longestSubarrWthSumDivByK(arr, n, k):
 
    # unordered map 'um' implemented as
    # hash table
    um = {}
 
    max_len = 0
    curr_sum = 0
 
    for i in range(n):
 
        curr_sum += arr[i]
        mod = ((curr_sum % k) + k) % k
        # if true then sum(0..i) is divisible by k
 
        if mod == 0:
            # update 'max_len'
            max_len = i + 1
 
        # if value 'mod_arr[i]' not present in 'um'
        # then store it in 'um' with index of its
        # first occurrence
        elif mod in um.keys():
            if max_len < (i - um[mod]):
                max_len = i - um[mod]
 
        else:
            um[mod] = i
 
    # return the required length of longest subarray with
    # sum divisible by 'k'
    return max_len
 
 
arr = [2, 7, 6, 1, 4, 5]
n = len(arr)
k = 3
print("Length =", longestSubarrWthSumDivByK(arr, n, k))
 
# This code is contributed by amreshkumar3, and updated by Kshitij Dwivedi


C#




using System;
using System.Collections.Generic;
 
// C# implementation to find the longest
// subarray with sum divisible by k
public class GFG {
 
    public static int
    longestSubarrWthSumDivByK(int[] arr, int n, int k)
    {
        // unordered map 'um' implemented as
        // hash table
        Dictionary<int, int> um
            = new Dictionary<int, int>();
 
        int max_len = 0;
        int curr_sum = 0;
 
        for (int i = 0; i < n; i++) {
            curr_sum += arr[i];
 
            int mod = ((curr_sum % k) + k) % k;
 
            // if true then sum(0..i) is divisible
            // by k
            if (mod == 0)
            // update 'max_len'
            {
                max_len = i + 1;
            }
 
            // if value 'mod' not present in 'um'
            // then store it in 'um' with index of its
            // first occurrence
            else if (um.ContainsKey(mod) == false) {
                um[mod] = i;
            }
 
            else {
                // if true, then update 'max'
                if (max_len < (i - um[mod])) {
                    max_len = i - um[mod];
                }
            }
        }
        // return the required length of longest subarray
        // with sum divisible by 'k'
        return max_len;
    }
 
    public static void Main(string[] args)
    {
        int[] arr = new int[] { 2, 7, 6, 1, 4, 5 };
        int n = arr.Length;
        int k = 3;
 
        Console.WriteLine(
            "Length = "
            + longestSubarrWthSumDivByK(arr, n, k));
    }
}
 
// This code is contributed by ishankhandelwals and updated
// by Kshitij Dwivedi


Javascript




<script>
// function to find the longest subarray
// with sum divisible by k
function longestSubarrWthSumDivByK(arr,n,k)
{
    // map 'um' implemented as
    // hash table
    let um = new Map();
 
    let max_len = 0;
    let curr_sum = 0;
 
    for (let i = 0; i < n; i++)
    {
        curr_sum += arr[i];
 
        let mod = ((curr_sum % k) + k) % k;
        // if true then sum(0..i) is divisible
        // by k
        if (mod == 0)
            // update 'max_len'
            max_len = i + 1;
 
        // if value 'mod_arr[i]' not present in 'um'
        // then store it in 'um' with index of its
        // first occurrence
        else if (um.has(mod) == false)
            um.set(mod,i);
 
        else
            // if true, then update 'max'
            if (max_len < (i - um.get(mod)))
            max_len = i - um.get(mod);
    }
 
    // required length of longest subarray with
    // sum divisible by 'k'
    return max_len;
}
 
// Driver program to test above
 
let arr = [2, 7, 6, 1, 4, 5];
let n = arr.length;
let k = 3;
 
document.write("Length = " + longestSubarrWthSumDivByK(arr, n, k));
 
// This code is contributed by shinjanpatra, and updated by Kshitij Dwivedi.
</script>


Output

Length = 4

Time Complexity: O(n), as we traverse the input array only once.
Auxiliary Space: O(min(n,k))



Previous Article
Next Article

Similar Reads

Longest subarray with sum not divisible by X
Given an array arr[] and an integer X, the task is to print the longest subarray such that the sum of its elements isn't divisible by X. If no such subarray exists, print "-1". Note: If more than one subarray exists with the given property, print any one of them.Examples: Input: arr[] = {1, 2, 3} X = 3 Output: 2 3 Explanation: The subarray {2, 3} h
15+ min read
Longest subarray with elements divisible by k
Suppose you are given an array. You have to find the length of the longest subarray such that each and every element of it is divisible by k.Examples: Input : arr[] = { 1, 7, 2, 6, 8, 100, 3, 6, 16}, k=2Output : 4 Input : arr[] = { 3, 11, 22, 32, 55, 100, 1, 5}, k=5Output : 2 Approach: Initialize two variables current_count and max_count with value
4 min read
Max sum of Subarray of length N/2 where sum is divisible by N
Given an array, arr[] of size N where N is even, the task is to find the maximum possible sum of the subarray of length N/2 where the sum is divisible by N. Examples: Input: arr[] = {2, 3, 4, 5, 6, 7}, N = 6Output:18Explanation: Here, N = 6, The maximum possible sum of a sublist of length 3 (N/2) is 18 (divisible by 6), which can be obtained by sel
8 min read
First subarray having sum at least half the maximum sum of any subarray of size K
Given an array arr[] and an integer K, the task is to find the first subarray which has a sum greater than or equal to half of the maximum possible sum from any subarray of size K. Examples: Input: arr[] = {2, 4, 5, 1, 4, 6, 6, 2, 1, 0}, K = 3 Output: 6 2 1 Explanation: The given array has a maximum possible sum from any subarray of size K is 16 fr
9 min read
Find a subarray whose sum is divisible by size of the array
Given an array arr[] of length N. The task is to check if there exists any subarray whose sum is a multiple of N. If there exists such subarray, then print the starting and ending index of that subarray else print -1. If there are multiple such subarrays, print any of them. Examples: Input: arr[] = {7, 5, 3, 7} Output: 0 1 Sub-array from index 0 to
13 min read
Length of smallest subarray to be removed to make sum of remaining elements divisible by K
Given an array arr[] of integers and an integer K, the task is to find the length of the smallest subarray that needs to be removed such that the sum of remaining array elements is divisible by K. Removal of the entire array is not allowed. If it is impossible, then print "-1". Examples: Input: arr[] = {3, 1, 4, 2}, K = 6Output: 1Explanation: Sum o
11 min read
Generate an N-length array having sum of each subarray divisible by K
Given two positive integers N and K, the task is to generate an array consisting of N distinct integers such that the sum of elements of each subarray of the constructed array is divisible by K. Examples: Input: N = 3, K = 3Output: 3 6 9Explanation:The subarrays of the resultant array are {3}, {6}, {3, 6}, {9}, {6, 9}, {3, 6, 9}. Sum of all these s
4 min read
Count ways to split an array into subarrays such that sum of the i-th subarray is divisible by i
Given an array arr[] consisting of N integers, the task is to find the number of ways to split the array into non-empty subarrays such that the sum of the ith subarray is divisible by i. Examples: Input: arr[] = {1, 2, 3, 4}Output: 3Explanation:Following are the number of ways to split the array into non-empty subarray as: Split the array into suba
8 min read
Non-Divisible Subarray sum permutation
Given a positive integer X, the task is to find a permutation of length X such that all subarray sum of length greater than one is not divisible by subarray length. If no permutation of length X exists, then print "Permutation doesn't exist". Examples: Input: X = 4Output: {2, 1, 4, 3}Explanation: All subarray sum of length greater than 1 isn't divi
6 min read
Subarray with no pair sum divisible by K
Given an array of N non-negative integers, task is to find the maximum size of a subarray such that the pairwise sum of the elements of this subarray is not divisible by a given integer, K. Also, print this subarray as well. If there are two or more subarrays that follow the above stated condition, then print the first one from the left. Prerequisi
13 min read
Generate an Array such that the sum of any Subarray is not divisible by its Length
Given an integer N. Then the task is to output an array let's say A[] of length N such that: The sum S, of any subarray, let's say A[L, R] where (L != R) must not leave the remainder as 0 when dividing by the length of A[L, R]. Formally, Sum(A[L, R])%(length of A[L, R]) != 0. A[] must contain all unique elements. Note: Subarrays must be chosen at l
5 min read
Count of longest possible subarrays with sum not divisible by K
Given an array of integers arr[] and a positive integer K, the task is to find the count of the longest possible subarrays with sum of its elements not divisible by K. Examples: Input: arr[] = {2, 3, 4, 6}, K = 3 Output: 1 Explanation: There is only one longest possible subarray of size 3 i.e. {3, 4, 6} having a sum 13, which is not divisible by K
9 min read
Longest subsequence whose sum is divisible by a given number
Given an array arr[] and an integer M, the task is to find the length of the longest subsequence whose sum is divisible by M. If there is no such sub-sequence then print 0. Examples: Input: arr[] = {3, 2, 2, 1}, M = 3 Output: 3 Longest sub-sequence whose sum is divisible by 3 is {3, 2, 1}Input: arr[] = {2, 2}, M = 3 Output: 0 Recommended: Please tr
15+ min read
Minimum cost to convert all elements of a K-size subarray to 0 from given Ternary Array with subarray sum as cost
Given an array arr[] of N integers, where each array element is either 0, 1, or 2, and an integer K, the task is to print the minimum cost needed to convert all the elements of the array to 0s by selecting a subarray of size K and converting any array element of the subarray to 0 in one operation with the cost equal to the sum of elements of the su
11 min read
Maximize the subarray sum after multiplying all elements of any subarray with X
Given an array arr[] of N integers and an integer X. We can choose any sub-array and multiply all its element by X. After multiplication, find the sub-array with the maximum sum. The task is to multiply the sub-array in such a way that the final sub-array sum is maximized. Examples: Input: arr[] = { -3, 8, -2, 1, -6 }, X = -1 Output: 15 Choose the
15+ min read
Find minimum subarray sum for each index i in subarray [i, N-1]
Given an array arr[] of size N, the task is to find the minimum subarray sum in the subarrays [i, N-1] for all i in [0, N-1]. Examples: Input: arr[ ] = {3, -1, -2}Output: -3 -3 -2Explanation: For (i = 1) i.e. {3, -1, -2}, the minimum subarray sum is -3 for {-1, -2}.For (i = 2) i.e. {-1, -2}, the minimum subarray sum is -3 for {-1, -2}.For (i = 3) i
9 min read
Maximize subarray sum by inverting sign of elements of any subarray at most twice
Given an array A of size n, find the maximum subarray sum after applying the given operation at most two times. In one operation, choose any two indices i and j and invert sign of all the elements from index i to index j, i.e, all positive elements in the range i to j become negative and all negative elements become positive. Examples: Input: A[] =
10 min read
Maximize product of min value of subarray and sum of subarray over all subarrays of length K
Given an array arr[] of N integers, the task is to find the maximum possible value of (min * sum) among all possible subarrays having K elements, where min denotes the smallest integer of the subarray and sum denotes the sum of all elements of the subarray. Example: Input: arr[] = {1, 2, 3, 2}, K = 3Output: 14Explanation: For the subarray {2, 3, 2}
7 min read
Count of subarray that does not contain any subarray with sum 0
Given an array arr, the task is to find the total number of subarrays of the given array which do not contain any subarray whose sum of elements is equal to zero. All the array elements may not be distinct.Examples: Input: arr = {2, 4, -6} Output: 5 Explanation: There are 5 subarrays which do not contain any subarray whose elements sum is equal to
11 min read
Longest Subarray with Sum greater than Equal to Zero
Given an array of N integers. The task is to find the maximum length subarray such that the sum of all its elements is greater than or equal to 0. Examples: Input: arr[]= {-1, 4, -2, -5, 6, -8} Output: 5 Explanation: {-1, 4, -2, -5, 6} forms the longest subarray with sum=2. Input: arr[]={-5, -6} Output: 0 Explanation: No such subarray is possible A
12 min read
Find longest subarray with Prime sum in given Array
Given an array arr[], the task is to find the longest subarray whose sum is a prime number. Examples: Input: arr[ ] = {1, 4, 2, 1}Output: 3Explanation: 4+2+1=7 and 7 is a prime number thus the subarray we get is {4, 2, 1} . Input: arr[ ] = {5, 2, 11, 4, 7, 19}Output: 5Explanation: 5+2+11+4+7=29 and 29 is a prime number thus the subarray we get is {
10 min read
Length of longest subarray having sum in given range [L, R]
Given an array arr[] of N integers, find the length of the longest subarray having sum in the range [L, R]. Examples: Input: arr[] = {1, 4, 6}, L = 3, R = 8Output: 2Explanation: The valid subarrays with there sum in range [3, 8] are {1, 4}, {4}, {6}. Longest subarray among them is {1, 4} having its length as 2. Input: arr[] = {15, 2, 4, 8, 9, 5, 10
7 min read
Find the longest Subarray with equal Sum and Product
Given an array arr[] of N integers, the task is to find the length of the longest subarray where the sum of the elements in the subarray is equal to the product of the elements in the subarray. Examples: Input: arr[] = [1, 2, 1, 2, 2, 5, 6, 24]Output: 5Explanation: The subarray [1, 2, 1, 2, 2] has a sum of 8 and a product of 8, hence it satisfies t
11 min read
Longest Subarray with sum differences ≤ K
Given a sorted array arr[] of size N, the task is to find the length of the longest subarray and print the subarray such that the sum of the differences of the maximum element of the chosen subarray with all other elements of that same subarray is ≤ K.i.e. ∑(amax-ai) ≤ K, for that given subarray. Examples: Input: N = 5, arr[] = {1, 4, 5, 6, 10}, K
7 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 maximum sum:First is {5}Second is {5, -2, -1, 3}Ther
12 min read
Longest subarray having sum K | Set 2
Given an array arr[] of size N containing integers. The task is to find the length of the longest sub-array having sum equal to the given value K. Examples: Input: arr[] = {2, 3, 4, 2, 1, 1}, K = 10 Output: 4 Explanation: The subarray {3, 4, 2, 1} gives summation as 10. Input: arr[] = {6, 8, 14, 9, 4, 11, 10}, K = 13 Output: 2 Explanation: The suba
14 min read
Longest subarray having sum of elements atmost K
Given an array arr[] of size N and an integer K, the task is to find the length of the largest subarray having the sum of its elements at most K, where K &gt; 0. Examples: Input: arr[] = {1, 2, 1, 0, 1, 1, 0}, k = 4Output: 5Explanation: {1, 2, 1} =&gt; sum = 4, length = 3 {1, 2, 1, 0}, {2, 1, 0, 1} =&gt; sum = 4, length = 4 {1, 0, 1, 1, 0} =&gt;5 s
12 min read
Maximum sum subarray having sum less than given sum using Set
Given an array arr[] of length N and an integer K, the task is the find the maximum sum subarray with a sum less than K.Note: If K is less than the minimum element, then return INT_MIN. Examples: Input: arr[] = {-1, 2, 2}, K = 4 Output: 3 Explanation: The subarray with maximum sum which is less than 4 is {-1, 2, 2}. The subarray {2, 2} has maximum
7 min read
Maximum sum subarray having sum less than or equal to given sum
Given an array of non-negative integers and a sum. We have to find sum of the subarray having a maximum sum less than or equal to the given sum in the array. Note: Given array contains only non-negative integers. Examples: Input: arr[] = { 1, 2, 3, 4, 5 } sum = 11Output: 10Subarray having maximum sum is { 1, 2, 3, 4 }Input: arr[] = { 2, 4, 6, 8, 10
10 min read
Find permutation of n which is divisible by 3 but not divisible by 6
Given an integer [Tex]n [/Tex]. The task is to find another integer which is permutation of n, divisible by 3 but not divisible by 6. Given that n is divisible by 6. If no such permutation is possible print -1. Examples: Input: n = 336 Output: 363 Input: n = 48 Output: -1 For a number to be divisible by 6, it must be divisible by 3 as well as 2, me
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg