如果数字为负数,为什么递归求解中查找给定序列中最大子序列的基本情况会返回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?
下面是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。
相关文章:
- 为什么这个递归没有得到它的基本情况?
- 如何在不销毁对象的情况下返回对象列表
- 基本的 c++ 问题:如果我在函数中创建某些内容并返回它会发生什么?
- 如何在不使用临时变量的情况下取消引用返回指针的函数的返回值?
- G++ 编译器是否在未使用返回值的情况下将 constexpr 函数视为常规函数?
- 模板元编程三元值未达到基本情况
- 递归楼梯中的基本情况
- C++ 循环链表的递归基本情况
- 如何在不使用返回的情况下从函数获取变量的地址(指针)
- 如何将递归函数(具有两个基本情况)转换为迭代函数
- 摆脱可变参数模板递归基本情况下不必要的类
- 具有空参数包的递归可变参数模板(以避免基本情况的重复)
- 返回返回基本或派生CLSS指针的功能值
- 使用递归进行硬币更改的基本情况是什么
- 为可变参数模板编写基本情况
- 如何在这个程序中编写关于递归的基本情况
- 如果数字为负数,为什么递归求解中查找给定序列中最大子序列的基本情况会返回0
- 具有许多基本情况的模板递归
- 可变函数模板基本情况:不带参数或带参数
- 为什么这个递归函数在基本情况似乎得到满足后继续被调用