import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* max length of the subarray sum = k
* @param arr int整型一维数组 the array
* @param k int整型 target
* @return int整型
*/
public int maxlenEqualK (int[] arr, int k) {
// write code here
if (arr == null || arr.length == 0) {
return 0;
}
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
// 最长子数组长度
int res = 0;
// 累加和
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
int temp = sum - k;
if (map.containsKey(temp)) {
res = Math.max(res, i - map.get(temp));
}
// 记录累加和
if (!map.containsKey(sum)) {
map.put(sum, i);
}
}
return res;
}
}