如果数字为负数,为什么递归求解中查找给定序列中最大子序列的基本情况会返回0

Why does the base case in recursive solution to find the maximum subsequence in a given sequence return 0 if the number is negative?

本文关键字:返回 基本情况 查找 数字 为什么 如果 递归      更新时间:2023-10-16

下面是C++中使用递归编写的示例代码,用于解决最大子序列问题-不完全是子序列,而是最大子序列的和。

int maxSumRec( const vector<int> & a, int left, int right )
{
  if( left == right ) // Base case
    if( a[ left]>0)
      return a[ left ];
    else
      return 0;
  int center = ( left + right ) / 2;
  int maxLeftSum = maxSumRec( a, left, center );
  int maxRightSum = maxSumRec( a, center + 1, right );
  int maxLeftBorderSum = 0, leftBorderSum = 0;
  for( int i = center; i >= left; --i )
  {
    leftBorderSum += a[ i ];
    if( leftBorderSum > maxLeftBorderSum )
      maxLeftBorderSum = leftBorderSum;
  }
  int maxRightBorderSum = 0, rightBorderSum = 0;
  for( int j = center + 1; j <= right; ++j )
  {
    rightBorderSum += a[ j ];
    if( rightBorderSum > maxRightBorderSum )
      maxRightBorderSum = rightBorderSum;
  }
  return max3( maxLeftSum, maxRightSum, maxLeftBorderSum + maxRightBorderSum );
}

如果剩下的单个元素为负数,为什么基本情况必须返回0?如果我们返回一个更高的值0而不是实际的负值,这不会影响总和吗?我在网上搜索了基本案例的解释和问题陈述,但找不到解释。

空序列{}{x}的子序列,其和为0。序列{x}的和为x,如果x为负,则明显小于0。