Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

find subarray with given sum

import java.util.*;

public class FindSubarrayWithGivenSum1 {
	static int findSubarray(int[] arr,int n,int sum){
		int start =0;
		int end = 1;
		int curr_sum= arr[0];

		while(end <=n){
			while(curr_sum>sum && start < end-1){
				curr_sum-=arr[start];
				start++;
			}

			if(curr_sum == sum){
				System.out.println("Subarray found at "+start+" "+(end-1));
				return 1;
			}

			if(end < n){
				curr_sum+=arr[end];
			}
			end++;
		}
		System.out.println("no subarray found.");
		return 0;

	}

	public static void main(String[] args){
		int[] arr = {1, 4, 20, 3, 10, 5};
		int n = arr.length;
		int s = 33;
		findSubarray(arr,n,s);
	}
}
Source by practice.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #find #subarray #sum
ADD COMMENT
Topic
Name
1+1 =