Tuesday, January 17, 2012

Maximum IntervalSum

#include<stdio.h>

int ara[20009] ;

int main(void)
{
int T, i, start, end, tcase=0, n, sum, max, index ;

scanf("%d",&T);

while( T-- )
{
scanf("%d",&n );

for( i=1;i<n;i++)
scanf("%d",&ara[i] );

index = max = sum = start = end = 0;

for(i=1;i<n;i++)
{
if( ara[i]+sum>=0 )
{
sum += ara[i] ;

if( !index ) index = i ;

if( sum>max )
{
start = index ;
end = i + 1 ;
max = sum ;
}
else if( sum == max )
{
if( i+1 - index > end - start )
{
start = index ;
end = i+1 ;
}
}
}

else if( ara[i]+sum<0 )
index = sum = 0;
}

if( start == 0 )
printf("Route %d has no nice parts\n",++tcase);

else printf("The nicest part of route %d is between stops %d and %d\n", ++tcase, start, end ) ;
}
return 0;
}
/*
Input:
3
3
  -1
   6
10
   4
  -5
   4
  -3
   4
   4
  -4
   4
  -5
4
  -2
  -3
  -4
  Output:
  The nicest part of route 1 is between stops 2 and 3
The nicest part of route 2 is between stops 3 and 9
Route 3 has no nice parts
*/

No comments:

Post a Comment