C++ 需要解决的可变性测试
我不明白这个问题,有人能澄清一下吗 更新:这是我使用Kadane算法的解决方案,但在以下阵列中失败:C++ 需要解决的可变性测试,c++,algorithm,vector,C++,Algorithm,Vector,我不明白这个问题,有人能澄清一下吗 更新:这是我使用Kadane算法的解决方案,但在以下阵列中失败: Example test: [-8, 3, 0, 5, -3, 12] WRONG ANSWER (got 17 expected 12) Example test: [-1, 2, 1, 2, 0, 2, 1, -3, 4, 3, 0, -1] WRONG ANSWER (got 12 expected 8) int max_so_far = 0, max_endi
Example test: [-8, 3, 0, 5, -3, 12]
WRONG ANSWER (got 17 expected 12)
Example test: [-1, 2, 1, 2, 0, 2, 1, -3, 4, 3, 0, -1]
WRONG ANSWER (got 12 expected 8)
int max_so_far = 0, max_ending_here = 0;
for (int i = 0; i < A.size(); i++)
{
max_ending_here = max_ending_here + A[i];
if (max_ending_here < 0)
max_ending_here = 0;
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
}
return max_so_far;
示例测试:[-8,3,0,5,-3,12]
回答错误(得到17个期望值12个)
示例测试:[-1,2,1,2,0,2,1,-3,4,3,0,-1]
回答错误(得到12个期望值8)
int max_so_far=0,max_ending_here=0;
对于(int i=0;i
该函数的外观与演示程序中显示的相同
#include <iostream>
#include <algorithm>
#include <vector>
long long int solution( const std::vector<int> &v )
{
long long int max_sum = 0;
for ( auto it = v.begin();
( it = std::find_if( it, v.end(), []( int x ) { return !( x < 0 ); } ) ) != v.end();
)
{
long long int sum = 0;
while ( it != v.end() && !( *it < 0 ) ) sum += *it++;
if ( max_sum < sum ) max_sum = sum;
}
return max_sum;
}
int main()
{
std::vector<int> v = { 1, 2, -3, 4, 5, -6 };
std::cout << solution( v ) << std::endl;
return 0;
}
可以使用索引而不是迭代器重写函数
至于你的功能,那么它是不正确的,至少相对于这个条件
if (max_ending_here < 0)
max_ending_here = 0;
if(此处的最大值<0)
此处的最大值=0;
因为条件不是检查当前元素是否小于零,而是检查当前元素的和。放弃赋值并说“我不明白”不是一个可以接受的问题。@CodyGray你能用清晰的英语向我解释一下吗,我不知道是切片(3,4)。从何处获得它。@andre数组的示例不正确,因为缺少索引为3的元素。:)我假设非负slice代表一个slice的非负和。然后你必须测试每个片段的总和,以找到最大值。@Polux66或数组的非负元素?我想知道我的算法中的错误,我使用的代码
if (max_ending_here < 0)
max_ending_here = 0;