編程演算法 - 連續和最大的子數組 代碼(C)

來源:互聯網
上載者:User

標籤:mystra   編程演算法   連續和最大的子數組   動態規劃   代碼   

連續和最大的子數組 代碼(C)


本文地址: http://blog.csdn.net/caroline_wendy


題目: 在一個數組中, 找出連續和最大的子序列.


使用兩個變數, 一個變數儲存當前值, 一個變數儲存最大值, 並設一個臨時數組, 用於更新最大和數組.

時間複雜度O(n).


代碼:

/* * 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;}

輸出:

18: 3 10 -4 7 2 





編程演算法 - 連續和最大的子數組 代碼(C)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.