-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Subarray.java
60 lines (55 loc) · 1.63 KB
/
Subarray.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/* Find Subarray of an array with given sum in O(n) time.
Input :
arr[]={1,4,20,3,10,5} ; sum=33
Output :
Sum found between indexes 2 and 4
*
*/
// to find Subarray of an array with given sum in O(n) time
import java.util.*;
class Subarray {
public static void findsubarray(List < Integer > arr, int sum) {
int startindex = 0, endindex = 0, tempsum = 0;
boolean flag = true;
while (tempsum != sum) {
if (tempsum < sum) {
tempsum += arr.get(endindex);
endindex += 1;
} else if (tempsum > sum) {
tempsum -= arr.get(startindex);
startindex += 1;
}
if (endindex == arr.size()) {
flag = false;
tempsum = sum;
}
}
if (flag)
System.out.println("Sum found between indexes " + startindex + " and " + (endindex - 1));
else
System.out.println(" No such subarray found");
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
List < Integer > arr = new ArrayList < > ();
System.out.print("Enter sum : ");
int sum = sc.nextInt();
System.out.println("Enter elements of array");
while (sc.hasNextInt())
arr.add(sc.nextInt());
//System.out.println(arr);
findsubarray(arr, sum);
}
}
/* Sample Input and Output :
* Enter sum : 33
Enter elements of array
1 4 20 3 10 5
Sum found between indexes 2 and 4
Enter sum : 33
Enter elements of array
1 4 20 3 20 5
No such subarray found
Time Complexity : O(n)
Space Complexity : O(1)
*/