需要解决的编码测试
A Codility test that needs to be solved
我看不懂这个问题,有人可以澄清一下吗?
更新 :这是我使用 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;
因为条件不是检查当前元素是否小于零,而是检查元素的当前总和。
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何确定我已使用非编码文件到达 EOF?
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 尽管测试成功,CppUnit测试核心仍被丢弃.为什么
- 数据成员SFINAE的C++17测试:gcc vs clang
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么二进制搜索在我的测试中不起作用
- 从父数组测试用例构造二叉树失败
- 试图对缓存进行跨步测试,但程序并没有结束
- 有什么好的方法可以让系统调用代理允许在单元测试中进行模拟
- OpenGL在启用深度测试时不会丢弃我的碎片
- 为测试目标创建具有不同源文件夹的文件
- 在子目录中使用target_sources()命令时用于单元测试(qtest)的项目结构
- 如何在性能和VMS上对C++进行代码审查/调试/编码/测试/版本控制
- 如何在VS编码的UI测试生成器的自定义控件中将测试提供程序从MSAA切换到UIA
- C++编码代码 青蛙河一号在大型排列测试中失败
- C++ 使用按钮执行编码的测试 UI.WINAPI (no MFC)
- 我如何使用Boost.Test硬编码跳过的测试
- 单元测试:对接口进行编码
- 需要解决的编码测试