题目链接:
-
#include <stdio.h>
-
-
int maxSubSum ( int *arr , int len ,int *from , int *to )
-
{
-
int currentSum , maxSum ;
-
int begin , end ;
-
-
currentSum = 0;
-
maxSum = -1;
-
-
begin = end = 0 ;
-
-
*from = *to = 0 ;
-
-
for ( int i = 0 ;i < len ; i++ )
-
{
-
currentSum += arr[i] ;
-
end = i ;
-
-
if ( currentSum > maxSum )
-
{
-
maxSum = currentSum ;
-
*from = begin ;
-
*to = end ;
-
}
-
if ( currentSum < 0 )
-
{
-
currentSum = 0 ;
-
begin = i+1 ;
-
}
-
}
-
return maxSum ;
-
}
-
-
int main ( void )
-
{
-
int K , arr[100000] ;
-
int from , to ,max ;
-
-
scanf ( "%d" , &K ) ;
-
-
for ( int i = 0 ; i < K ; i++ )
-
{
-
scanf ("%d" , &arr[i]) ;
-
}
-
-
-
max = maxSubSum ( arr , K-1 , &from , &to ) ;
-
-
if ( max >= 0 )
-
printf ("%d %d %d" , max , arr[from] , arr[to] ) ;
-
-
else
-
printf ("0 %d %d" , arr[0] , arr[K-1]) ;
-
-
return 0 ;
-
}
一个 4 分的测试点没有通过
将上面代码中的 48 行 的 K -1 修改成为 K值之后,通过所有的测试点,大体思想不变
题目中有一点要求是需要格外注意的,那边是:
1. 数列中全部数均为负数 , 输出 max = 0 , 和原数列中的首尾元素值
2. 数列中存在 1 到多个 数值为0 的元素,其余元素均为负数,输出 max = 0 ,和首个 0 元素出现的序列
这两种情况必须加以区分,所以在对 max 进行初始化的时候,不能将其设定为 0
应该将其设定为 -1 才可以
-
#include <stdio.h>
-
#include <stdlib.h>
-
-
int maxSubSum ( int *arr , int len ,int *from , int *to )
-
{
-
int currentSum , maxSum ;
-
int begin , end ;
-
-
currentSum = 0 ;
-
maxSum = -1 ;
-
-
begin = end = 0 ;
-
-
*from = *to = 0 ;
-
-
for ( int i = 0 ;i < len ; i++ )
-
{
-
currentSum += arr[i] ;
-
end = i ;
-
-
if ( currentSum > maxSum )
-
{
-
maxSum = currentSum ;
-
*from = begin ;
-
*to = end ;
-
}
-
if ( currentSum < 0 )
-
{
-
currentSum = 0 ;
-
begin = i+1 ;
-
}
-
}
-
return maxSum ;
-
}
-
-
int main ( void )
-
{
-
int K , arr[100000] ;
-
int from , to ,max ;
-
-
scanf ( "%d" , &K ) ;
-
-
for ( int i = 0 ; i < K ; i++ )
-
{
-
scanf ("%d" , &arr[i]) ;
-
}
-
max = maxSubSum ( arr , K , &from , &to ) ;
-
-
if ( max >= 0 )
-
printf ("%d %d %d" , max , arr[from] , arr[to] ) ;
-
-
else
-
printf ("0 %d %d" , arr[0] , arr[K-1] ) ;
-
-
return 0 ;
-
}
阅读(735) | 评论(0) | 转发(0) |