-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathMaximum_Subarray_Sum1.c
64 lines (56 loc) · 1.24 KB
/
Maximum_Subarray_Sum1.c
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
// To find the maximum subarray sum
// Complexity: O(n^3)
#include<stdio.h>
int main()
{
int n,a[100],maxSum=0,currSum=0,left=-1,right=-1;
printf("Enter the size of the array: ");
scanf("%d",&n);
printf("Enter the elements of the array:\n");
for (int i = 0; i < n; i++)
{
scanf("%d",&a[i]);
}
for (int i = 0; i < n; i++)
{
for (int j = i; j < n; j++)
{
currSum=0;
for (int k = i; k<=j; k++)
{
currSum+=a[k];
}
// Update the maxSum if the currSum is greater than maxSum
if (currSum>maxSum)
{
maxSum=currSum;
left=i;
right=j;
}
}
}
// To print the maximum sum of the subarray
printf("Maximum subarray sum: %d\n",maxSum);
// To print the subarray
printf("The subarray is: {");
for (int k = left; k <=right ; k++)
{
printf(" %d",a[k]);
}
printf(" }");
return 0;
}
/* OUTPUT:-
Enter the size of the array: 8
Enter the elements of the array:
-2
-5
6
-2
-3
1
5
-6
Maximum subarray sum: 7
The subarray is: { 6 -2 -3 1 5 }
*/