-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaximum Subsequence Sum
66 lines (65 loc) · 1.22 KB
/
Maximum Subsequence Sum
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
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define N 10000
int main()
{
int a[N], n, i, j=0, k=0, b[N];
int flag=-1;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
if(a[i]>=0)
{
flag=1;
}
}
if(flag==-1)
{
printf("0 %d %d",a[0],a[n-1]);
}
else
{
int maxSum=0, thisSum=0;
for(i=0;i<n;i++)
{
if(thisSum+a[i]<0)
{
thisSum=0;
if(a[i+1]>=0)
{
b[j]=i+1;
j++;
if(k==0)
{
k=i+1;
}
}
}
else
{
thisSum+=a[i];
}
if(maxSum<thisSum)
{
maxSum=thisSum;
k=i;
}
}
while(b[j-1]>k&&j!=1)
{
j--;
}
if(j==0)
{
printf("%d %d %d",maxSum, a[b[0]], a[k]);
}
else
{
printf("%d %d %d",maxSum, a[b[j-1]], a[k]);
}
}
return 0;
}