Cod sursa(job #3229765)

Utilizator tudor_cretuCretu Mihnea Tudor tudor_cretu Data 17 mai 2024 13:58:50
Problema Subsecventa de suma maxima Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main() {
    ifstream fin("ssm.in");
    ofstream fout("ssm.out");
    int n;
    fin >> n;

    vector<int> a(n);
    for (int i = 0; i < n; i++) {
        fin >> a[i];
    }

    int max_sum = a[0];
    int current_sum = a[0];
    int start_current = 1;
    int start_best = 1;
    int end_best = 1;
    int length_best = 1;

    for (int i = 1; i < n; i++) {
        if (current_sum + a[i] < a[i]) {
            current_sum = a[i];
            start_current = i + 1;
        } else {
            current_sum += a[i];
        }

        if (current_sum > max_sum) {
            max_sum = current_sum;
            start_best = start_current;
            end_best = i + 1;
            length_best = end_best - start_best + 1;
        } else if (current_sum == max_sum) {
            int current_length = i + 1 - start_current + 1;
            if (start_current < start_best || (start_current == start_best && current_length < length_best)) {
                start_best = start_current;
                end_best = i + 1;
                length_best = current_length;
            }
        }
    }

    fout << max_sum << " " << start_best << " " << end_best << endl;

    fin.close();
    fout.close();
    return 0;
}