求整数数组中和最大的子数组
来源:互联网 发布:安卓源码网 编辑:程序博客网 时间:2024/05/17 01:53
struct maxInfo{ int start; int end; int max;};bool maxValue(int a[], int n, maxInfo& mi ){ if( n < 0 ) { return false;} mi.start = mi.end = 0; mi.max = a[0]; int i; int curValue = mi.max; for( i = 1; i < n ; i ++) { if(curValue + a[i] > mi.max) { if(curValue < 0 ) { mi.start = mi.end = i; mi.max = a[i]; curValue = a[i]; } else { mi.end = i; mi.max += a[i]; curValue +=a[i]; } } else { curValue += a[i]; } } return true;}
算法很简单,如下:
测试代码如下:
#include <iostream>#include <vector>#include <iterator>#include <istream>using namespace std;struct maxInfo{ int start; int end; int max;};void maxValue(vector<int> a, maxInfo &mi){ mi.start = mi.end = 0; mi.max = a[0]; int i; int curValue = mi.max; int n = a.size(); for( i = 1; i < n ; i ++) { if(curValue + a[i] > mi.max) { if(curValue < 0 ) { mi.start = mi.end = i; mi.max = a[i]; curValue = a[i]; } else { mi.end = i; mi.max += a[i]; curValue +=a[i]; } } else { curValue += a[i]; } }}int main(){ maxInfo mi; cout << "Input the datas : " ; istream_iterator<int> begin(cin), end; vector<int> vc(begin, end); maxValue(vc, mi); cout << "[ " << mi.start << ", " << mi.end << " ]" << endl; cout << "Max value is: " << mi.max <<endl; cout << "Sub array is : " <<endl; copy(vc.begin() + mi.start, vc.begin() + mi.end + 1, ostream_iterator<int> (cout, " ")); return 0;}
- 求整数数组中和最大的子数组
- 求整数数组中和最大的子数组
- 求数组中和最大的子数组
- 求数组中和最大的子序列
- 求数组中和最大的子序列
- 求整数数组中和最大的子数组的3种方法
- 求数组中和最大的子数组(数组中和最大的子串)
- 求数组中和最大的子数组(数组中和最大的子串)
- 求数组中和最大的子数组【算法】
- C#求数组中和最大的连续子数组
- 求数组中和最大的子数组与始末下标
- 求数组中和最大子序列
- 求数组中和最大的子数组并输出子数组序列
- 求一个整数数组的子数组的最大和
- 寻找数组中和最大的子序列
- 数组中和最大的递增子序列
- 如何查找数组中和最大的子序列
- 求数组中和最大的一串数据
- libevent源码深度剖析八
- 2013年上半年系统集成项目管理工程师-网络版
- OD插件详解
- Web前端开发
- 消息队列客户端转发MQClinet2.6版
- 求整数数组中和最大的子数组
- access数据库出现操作必须使用一个可更新的查询的解决办法
- java socket编程
- 个人建立虚拟局域网的一点心得(hamachi)
- 关于mysql的命令的一些用法
- 将CString(Unicode) 转成 char 以下可转中文
- 关于等待队列
- 第十三周----课本例题11.7
- android(7)_数据存储与访问1_文件