连续和最大的子数组 代码(C)

/*
 * main.cpp
 *
 *  Created on: 2014.9.19
 *      Author: spike
 */

#include <iostream>
#include <vector>
#include <climits>

using namespace std;

int FindSequence (int data[], int length, vector<int>& vi){
 if (data == NULL || length <= 0)
  return INT_MIN;
 int greatest = INT_MIN;
 int cur = 0;
 vector<int> tmp;

for (int i=0; i<length; ++i) {
  if (cur <= 0) {
   cur = data[i];
   tmp.clear();
   tmp.push_back(data[i]);
  } else {
   cur += data[i];
   tmp.push_back(data[i]);
  }

if (cur > greatest) {
   vi = tmp;
   greatest = cur;
  }
 }
 return greatest;
}

int main(void)
{
 int data[] = {1, -2, 3, 10, -4, 7, 2, -5};
 int length = sizeof(data)/sizeof(data[0]);
 vector<int> vi;
 int g = FindSequence(data, length, vi);
 cout << g << ": ";
 for (size_t i=0; i<vi.size(); ++i) {
  cout << vi[i] << " ";
 }
 cout << endl;

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/5ac3ebb34c9c129e5070af101844b3e2.html