求和小于k的最长子数组的最优解

public static int maxLength(int[] arr, int k){
	if(arr == null || arr.length == 0){
		return 0;
	}
	int[] sums = new int[arr.length];
	HashMap ends = new HashMap();
	sums[arr.length - 1] = arr[arr.length - 1];
	ends.put(arr.length - 1, arr.length - 1);
	for(int i = arr.length - 2; i>= 0; i--){
		if(sum[i + 1] < 0){
			sums[i] = arr[i] + sums[i + 1];
			ends.put(i, ends.get(i + 1));
		}else{
			sums[i] = arr[i];
			ends.put(i, i);
		}
	}
	
	int end = 0;
	int sum = 0;
	int res = 0;
	for(int i = 0; i < arr.length; i++){
		while(end < arr.length && sum + sums[end] <= k){
			sum += sums[end];
			end = ends.get(end) + 1;
		}
		sum -= end > i ? arr[i] : 0;
		res = Math.max(res, end - i);
		end = Math.max(end, i + 1);
	}
	return res;
}

你可能感兴趣的:(最长子数组,算法,数据结构)