-
Notifications
You must be signed in to change notification settings - Fork 0
/
findcontinuoussum.cs
80 lines (65 loc) · 1.74 KB
/
findcontinuoussum.cs
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using System;
// To execute C#, please define "static void Main" on a class
// named Solution.
class Solution
{
static void Main(string[] args)
{
int[] arr = new int[8] {15, 2, 4, 8, 9, 5, 10, 23};
int sum = 23;
contiguoussum(arr, sum);
findcontinuoussum(arr, sum);
}
public static bool findcontinuoussum(int[] arr, int sum)
{
int length = arr.Length;
int calcsum = 0;
int j =0;
for(int i=0; i<length; i++)
{
while(j < length && calcsum < sum)
{
calcsum = calcsum + arr[j];
j++;
}
if(calcsum == sum)
{
Console.WriteLine("found sum");
return true;
}
calcsum = calcsum - arr[i];
}
return false;
}
public static void contiguoussum(int[] arr, int sum)
{
int length = arr.Length;
int curr_sum =0;
int i = 0;
int j = 0;
int ix=0;
int iy=0;
for(i=0; i<length; i++)
{
curr_sum = arr[i];
for(j=i+1; j<length; j++)
{
if(curr_sum == sum)
{
ix=i;
iy= j-1;
Console.WriteLine("SubArray from: " + ix + " and " + iy);
return;
}
if(curr_sum > sum)
{
break;
}
else
{
curr_sum = curr_sum + arr[j];
}
}
}
}
}