需要解决的编码测试

A Codility test that needs to be solved

本文关键字:编码 测试 解决      更新时间:2023-10-16

我看不懂这个问题,有人可以澄清一下吗?

更新 :这是我使用 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_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;

该函数的外观可以像演示程序中显示的那样

#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;
}

它的输出是

9

您可以使用索引而不是迭代器重写函数。

至于你的函数,那么至少相对于这个条件它是不正确的

    if (max_ending_here < 0)
        max_ending_here = 0;

因为条件不是检查当前元素是否小于零,而是检查元素的当前总和。