C++ 最长子段和

 最大子段和详解_最大字段和_Niteip的博客-优快云博客

#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <algorithm>
#include <climits>
#include <unordered_map>
#include <set>

using namespace std;

vector<int> read_line_data();
vector<int> read_line_data(char split);
void output_data(const vector<int>& data);

int main() {
    vector<int> a = read_line_data(',');
    int n = a.size();
    vector<int> b(n, 0);
    int max_v = INT_MIN;
    int left = 0;
    int right = 0;
    b[0] = a[0];
    for (int i = 1; i < n; i++) {
        if (b[i - 1] >= 0) {
            b[i] = b[i - 1] + a[i];
        } else {
            b[i] = a[i];
            left = i;
        }
        if (max_v < b[i]) {
            max_v = b[i];
            right = i;
        }
    }

    cout << max_v << " " << left << " " << right << endl;

}

vector<int> read_line_data() {
    string src;

    getline(cin, src);
    istringstream iss(src);

    vector<int> data;
    int token;
    while (iss >> token) {
        data.push_back(token);
    }

    return data;
}

vector<int> read_line_data(char split) {
    string input;

    cin >> input;
    vector<int> data;
    stringstream ss(input);
    string token;
    while (getline(ss, token, split)) {
        int value = stoi(token);
        data.push_back(value);
    }

    return data;
}

void output_data(const vector<int>& data) {
    int n = data.size();
    for (int i = 0; i < n; i++) {
        cout << data[i] << " ";
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值