Question:
How to find the longest subarray with sum divisible by K using Java

Summary

Let’s assume:

Method- longSubarrWthSumDivByK

Integer- a[], n, k


Solution


//User function Template for Java


class Solution{

    int longSubarrWthSumDivByK(int a[], int n, int k)


    { int sum = 0;

        int maxLength = 0;

      HashMap<Integer, Integer> remainderMap = new HashMap<>();


        for (int i = 0; i < n; i++) {

            sum += a[i];


            // Calculate the remainder when divided by K

            int remainder = (sum % k + k) % k;


            // If remainder is 0, update maxLength to current length

            if (remainder == 0) {

                maxLength = i + 1;

            }

            // If remainder is seen before, update maxLength with the difference of current index and previous index

            else if (remainderMap.containsKey(remainder)) {

                maxLength = Math.max(maxLength, i - remainderMap.get(remainder));

            }

            // If remainder is not seen before, add it to the HashMap with its index

            else {

                remainderMap.put(remainder, i);

            }

        }


        return maxLength;

    }

}


Suggested blogs:

>How to make count consistent across numbers?


>How to return the subarray indexes from left to right using Java

>How to return the sum of subarray with maximum sum

>How to print all the paths from the root with a specified sum using Java

>Building Web API using ASP.NET (C#)

>Built Web API using ASP.NET (C#)


Nisha Patel

Nisha Patel

Submit
0 Answers