Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,939 questions

51,876 answers

573 users

How to find the maximum length of a subarray having a sum equal to K in Java

1 Answer

0 votes
import java.util.HashMap;

public class MyClass {
    static int maxSubArrayLenEqualsToK(int[] arr, int k) {
        int current = 0, len = 0;
        
        HashMap<Integer, Integer> hmap = new HashMap<>();
        
        int size = arr.length;
        
        for (int i = 0; i < size; i++) {
            current += arr[i];
            if (current == k) {
                len = i + 1;
            }
            else if (hmap.containsKey(current - k)) {
                len = Math.max(len, i - hmap.get(current - k));
            }
            if (!hmap.containsKey(current)) {
                hmap.put(current, i);
            }
        }
        
        return len;
    }
 
    public static void main(String args[]) {
        int[] arr = {1, -1, 5, -2, -3, 2, 3, 3};
 
        int K = 3;
        
        // 1, -1, 5, -2 = 3 (4)
        // 5, -2 = 3 (2)
        // -2, -3, 2, 3, 3 = 3 (5)
        
        System.out.print(maxSubArrayLenEqualsToK(arr, K));
    }
}
 
 
 
/*
run:

5

*/

 



answered Feb 23, 2024 by avibootz
...