Skip to content

Commit 1053ee8

Browse files
committed
Update problem25.c
1 parent 2e72f7d commit 1053ee8

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

problem25.c

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,88 @@ int main()
3535
}
3636
//Time Complexity: O(n)
3737

38+
//By Nandha Kumar, ECE
39+
#include<stdio.h>
40+
41+
int FindMaxSum(int arr[], int n)
42+
43+
{
44+
45+
int incl = arr[0];
46+
47+
int excl = 0;
48+
49+
int exclnew;
50+
51+
int i;
52+
53+
for (i = 1; i < n; i++)
54+
55+
{
56+
57+
exclnew = (incl > excl)? incl: excl;
58+
59+
incl = excl + arr[i];
60+
61+
excl = exclnew;
62+
63+
}
64+
65+
return ((incl > excl)? incl : excl);
66+
67+
}
68+
69+
int main()
70+
71+
{
72+
73+
int arr[] = {5, 5, 10, 100, 10, 5};
74+
75+
printf("%d \n", FindMaxSum(arr, 6));
76+
77+
getchar();
78+
79+
return 0;
80+
81+
}
82+
83+
//how the program works
84+
85+
arr[] = {5, 5, 10, 40, 50, 35}
86+
87+
inc = 5
88+
89+
exc = 0
90+
91+
For i = 1 (current element is 5)
92+
93+
incl = (excl + arr[i]) = 5
94+
95+
excl = max(5, 0) = 5
96+
97+
For i = 2 (current element is 10)
98+
99+
incl = (excl + arr[i]) = 15
100+
101+
excl = max(5, 5) = 5
102+
103+
For i = 3 (current element is 40)
104+
105+
incl = (excl + arr[i]) = 45
106+
107+
excl = max(5, 15) = 15
108+
109+
For i = 4 (current element is 50)
110+
111+
incl = (excl + arr[i]) = 65
112+
113+
excl = max(45, 15) = 45
114+
115+
For i = 5 (current element is 35)
116+
117+
incl = (excl + arr[i]) = 80
118+
119+
excl = max(5, 15) = 65
120+
121+
And 35 is the last element. So, answer is max(incl, excl) = 80
122+

0 commit comments

Comments
 (0)