Length of the longest subarray with K sum
Optimalunknown
java
9 months ago
1.5 kB
5
Indexable
//{ Driver Code Starts
import java.io.*;
import java.util.*;
class Geeks {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine()); // Number of test cases
for (int g = 0; g < t; g++) {
// Read input array as a string, split by space, and convert to integers
String[] str = br.readLine().trim().split(" ");
int arr[] = new int[str.length];
for (int i = 0; i < str.length; i++) {
arr[i] = Integer.parseInt(str[i]);
}
// Print the result from maxLen function
System.out.println(new Solution().maxLen(arr));
System.out.println("~");
}
}
}
// } Driver Code Ends
class Solution {
int maxLen(int arr[]) {
int i, j, k;
int sum = 0, maxi=0, n=arr.length;
HashMap<Integer, Integer> hmp = new HashMap<>();
for(i=0;i<n;++i)
{
sum += arr[i];
if(sum==0)
{
maxi = Math.max(maxi, i+1);
}
else if(hmp.get(sum))
{
maxi = Math.max(maxi, i - hmp.get(sum));
}
else
{
hmp.put(sum, i);
}
}
return maxi;
}
}
Editor is loading...
Leave a Comment