Continuous and maximum sub-array code (c)
Address: http://blog.csdn.net/caroline_wendy
Question: In an array, find the continuous and maximum subsequences.
Use two variables, one to store the current value, one to store the maximum value, and a temporary array to update the maximum and array.
Time complexity O (n ).
Code:
/* * 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; return 0;}
Output:
18: 3 10 -4 7 2
Programming algorithms-continuous and maximum sub-array code (c)