find subarray with given sum

Solutions on MaxInterview for find subarray with given sum by the best coders in the world

showing results for - "find subarray with given sum"
Bilel
30 Mar 2018
1import java.sql.Array;
2import java.util.ArrayList;
3import java.util.Arrays;
4
5public class FindSubArr {
6    public static void main(String[] args) {
7        int [] arr = {0,1,2,3,4,5,6,9,2,1,1,1,10,2,2,2};
8        int s = 6 ;
9        int [] sub = findLongestSubArray( arr,s);
10        System.out.println("longest SubArray Range ==> "+Arrays.toString(sub));
11
12    }
13
14    public static int[] findLongestSubArray(int [] arr, int s){
15
16        int[] result = new int[]{-1};
17        int sum=0,left=0,right=0;
18
19        while(right < arr.length){
20            sum += arr[right];
21            while(left < right && sum > s){
22                sum -= arr[left++];
23            }
24            if(sum == s && (result.length == 1 || result[1] - result[0] < right - left)){
25                result = new int[]{left + 1, right +1};
26            }
27            right++;
28        }
29        return result;
30    }
31}
32
similar questions
queries leading to this page
find subarray with given sum