标签:tle print log private == dex demo1 maxlength length
package com.hzins.suanfa; /** * 累加和小于或等于定值得最长子数组的长度 * @author Administrator * */ public class Demo1 { public static int maxLength(int[] arr, int k){ int[] h = new int[arr.length + 1]; int sum = 0; h[0] = sum; for(int i = 0;i !=arr.length;i ++){ sum +=arr[i]; h[i + 1] = h[i] + Math.max(sum, h[i]); } sum = 0; int res= 0; int pre= 0; int len = 0; for(int i = 0;i != arr.length;i++){ sum +=arr[i]; pre = getLessIndex(h, sum - k); len = pre == -1 ? 0 : i - pre + 1; res = Math.max(res, len); } return res; } /** * 在【】h中第一个大于等于i的数的位置 * @param h * @param i * @return */ private static int getLessIndex(int[] h, int i) { int left = 0; int right = h.length - 1; int mid = 0; int res = -1; while(left <= right){ mid = (left + right) / 2; if(h[mid] >= i){ right = mid - 1; res = mid; }else{ left = mid + 1; } } return res; } public static void main(String[] args) { int[] array = {1,-2,3,-4,5,6,-6,7,-7,8}; System.out.println(maxLength(array, -1)); } }
标签:tle print log private == dex demo1 maxlength length
原文地址:http://www.cnblogs.com/caobojia/p/6785404.html