IncredibleThings

导航

HackerRank-Longest Subarray

give an array and target value, find the max length of the subarray which sum of the elements is less or equal to that value. 

 

 

    public int longestSubArray(int[] a, int k){
        if(a==null || a.length==0){
            return 0;
        }
        int max=0;
        int len=a.length;
        for(int i=0; i<len; i++){
            int start=a[i];
            if(start >= k){
                if(max<1){
                    max=1;
                }
            }
            else{
                int sum=start;
                for(int j=i+1; j<len; j++){
                    sum=sum+a[j];
                    if(sum>k){
                        if(max<(j-i)){
                            max=j-i;
                        }
                        break;
                    }
                    
                    if(sum <= k && j==(len-1)){
                        if(max<(j-i+1)){
                            max=j-i+1;
                        }
                    }
                }
            }
        }
        return max;
    }

 

posted on 2016-09-29 23:32  IncredibleThings  阅读(478)  评论(0编辑  收藏  举报